Server Modules

server_modules

__init__.

class server_modules.JSON(none_as_null: bool = False)

기반 클래스: Indexable, TypeEngine

Represent a SQL JSON type.

참고

_types.JSON is provided as a facade for vendor-specific JSON types. Since it supports JSON SQL operations, it only works on backends that have an actual JSON type, currently:

  • PostgreSQL - see sqlalchemy.dialects.postgresql.JSON and sqlalchemy.dialects.postgresql.JSONB for backend-specific notes

  • MySQL - see sqlalchemy.dialects.mysql.JSON for backend-specific notes

  • SQLite as of version 3.9 - see sqlalchemy.dialects.sqlite.JSON for backend-specific notes

  • Microsoft SQL Server 2016 and later - see sqlalchemy.dialects.mssql.JSON for backend-specific notes

_types.JSON is part of the Core in support of the growing popularity of native JSON datatypes.

The _types.JSON type stores arbitrary JSON format data, e.g.:

data_table = Table(
    "data_table",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("data", JSON),
)

with engine.connect() as conn:
    conn.execute(
        data_table.insert(), {"data": {"key1": "value1", "key2": "value2"}}
    )

JSON-Specific Expression Operators

The _types.JSON datatype provides these additional SQL operations:

  • Keyed index operations:

    data_table.c.data["some key"]
    
  • Integer index operations:

    data_table.c.data[3]
    
  • Path index operations:

    data_table.c.data[("key_1", "key_2", 5, ..., "key_n")]
    
  • Data casters for specific JSON element types, subsequent to an index or path operation being invoked:

    data_table.c.data["some key"].as_integer()
    

    Added in version 1.3.11.

Additional operations may be available from the dialect-specific versions of _types.JSON, such as sqlalchemy.dialects.postgresql.JSON and sqlalchemy.dialects.postgresql.JSONB which both offer additional PostgreSQL-specific operations.

Casting JSON Elements to Other Types

Index operations, i.e. those invoked by calling upon the expression using the Python bracket operator as in some_column['some key'], return an expression object whose type defaults to _types.JSON by default, so that further JSON-oriented instructions may be called upon the result type. However, it is likely more common that an index operation is expected to return a specific scalar element, such as a string or integer. In order to provide access to these elements in a backend-agnostic way, a series of data casters are provided:

These data casters are implemented by supporting dialects in order to assure that comparisons to the above types will work as expected, such as:

# integer comparison
data_table.c.data["some_integer_key"].as_integer() == 5

# boolean comparison
data_table.c.data["some_boolean"].as_boolean() == True

Added in version 1.3.11: Added type-specific casters for the basic JSON data element types.

참고

The data caster functions are new in version 1.3.11, and supersede the previous documented approaches of using CAST; for reference, this looked like:

from sqlalchemy import cast, type_coerce
from sqlalchemy import String, JSON

cast(data_table.c.data["some_key"], String) == type_coerce(55, JSON)

The above case now works directly as:

data_table.c.data["some_key"].as_integer() == 5

For details on the previous comparison approach within the 1.3.x series, see the documentation for SQLAlchemy 1.2 or the included HTML files in the doc/ directory of the version’s distribution.

Detecting Changes in JSON columns when using the ORM

The _types.JSON type, when used with the SQLAlchemy ORM, does not detect in-place mutations to the structure. In order to detect these, the sqlalchemy.ext.mutable extension must be used, most typically using the MutableDict class. This extension will allow “in-place” changes to the datastructure to produce events which will be detected by the unit of work. See the example at HSTORE for a simple example involving a dictionary.

Alternatively, assigning a JSON structure to an ORM element that replaces the old one will always trigger a change event.

Support for JSON null vs. SQL NULL

When working with NULL values, the _types.JSON type recommends the use of two specific constants in order to differentiate between a column that evaluates to SQL NULL, e.g. no value, vs. the JSON-encoded string of "null". To insert or select against a value that is SQL NULL, use the constant null(). This symbol may be passed as a parameter value specifically when using the _types.JSON datatype, which contains special logic that interprets this symbol to mean that the column value should be SQL NULL as opposed to JSON "null":

from sqlalchemy import null

conn.execute(table.insert(), {"json_value": null()})

To insert or select against a value that is JSON "null", use the constant _types.JSON.NULL:

conn.execute(table.insert(), {"json_value": JSON.NULL})

The _types.JSON type supports a flag :paramref:`_types.JSON.none_as_null` which when set to True will result in the Python constant None evaluating to the value of SQL NULL, and when set to False results in the Python constant None evaluating to the value of JSON "null". The Python value None may be used in conjunction with either _types.JSON.NULL and null() in order to indicate NULL values, but care must be taken as to the value of the :paramref:`_types.JSON.none_as_null` in these cases.

Customizing the JSON Serializer

The JSON serializer and deserializer used by _types.JSON defaults to Python’s json.dumps and json.loads functions; in the case of the psycopg2 dialect, psycopg2 may be using its own custom loader function.

In order to affect the serializer / deserializer, they are currently configurable at the _sa.create_engine() level via the :paramref:`_sa.create_engine.json_serializer` and :paramref:`_sa.create_engine.json_deserializer` parameters. For example, to turn off ensure_ascii:

engine = create_engine(
    "sqlite://",
    json_serializer=lambda obj: json.dumps(obj, ensure_ascii=False),
)

버전 1.3.7에서 변경: SQLite dialect’s json_serializer and json_deserializer parameters renamed from _json_serializer and _json_deserializer.

더 보기

sqlalchemy.dialects.postgresql.JSON

sqlalchemy.dialects.postgresql.JSONB

sqlalchemy.dialects.mysql.JSON

sqlalchemy.dialects.sqlite.JSON

hashable = False

Flag, if False, means values from this type aren’t hashable.

Used by the ORM when uniquing result lists.

NULL = symbol('JSON_NULL')

Describe the json value of NULL.

This value is used to force the JSON value of "null" to be used as the value. A value of Python None will be recognized either as SQL NULL or JSON "null", based on the setting of the :paramref:`_types.JSON.none_as_null` flag; the _types.JSON.NULL constant can be used to always resolve to JSON "null" regardless of this setting. This is in contrast to the _expression.null() construct, which always resolves to SQL NULL. E.g.:

from sqlalchemy import null
from sqlalchemy.dialects.postgresql import JSON

# will *always* insert SQL NULL
obj1 = MyObject(json_value=null())

# will *always* insert JSON string "null"
obj2 = MyObject(json_value=JSON.NULL)

session.add_all([obj1, obj2])
session.commit()

In order to set JSON NULL as a default value for a column, the most transparent method is to use _expression.text():

Table(
    "my_table", metadata, Column("json_data", JSON, default=text("'null'"))
)

While it is possible to use _types.JSON.NULL in this context, the _types.JSON.NULL value will be returned as the value of the column, which in the context of the ORM or other repurposing of the default value, may not be desirable. Using a SQL expression means the value will be re-fetched from the database within the context of retrieving generated defaults.

__init__(none_as_null: bool = False)

Construct a _types.JSON type.

매개변수:

none_as_null=False

if True, persist the value None as a SQL NULL value, not the JSON encoding of null. Note that when this flag is False, the null() construct can still be used to persist a NULL value, which may be passed directly as a parameter value that is specially interpreted by the _types.JSON type as SQL NULL:

from sqlalchemy import null

conn.execute(table.insert(), {"data": null()})

참고

:paramref:`_types.JSON.none_as_null` does not apply to the values passed to :paramref:`_schema.Column.default` and :paramref:`_schema.Column.server_default`; a value of None passed for these parameters means “no default present”.

Additionally, when used in SQL comparison expressions, the Python value None continues to refer to SQL null, and not JSON NULL. The :paramref:`_types.JSON.none_as_null` flag refers explicitly to the persistence of the value within an INSERT or UPDATE statement. The _types.JSON.NULL value should be used for SQL expressions that wish to compare to JSON null.

더 보기

types.JSON.NULL

class JSONElementType

기반 클래스: TypeEngine

Common function for index / path elements in a JSON expression.

bind_processor(dialect)

Return a conversion function for processing bind values.

Returns a callable which will receive a bind parameter value as the sole positional argument and will return a value to send to the DB-API.

If processing is not necessary, the method should return None.

참고

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it’s not feasible to subclass a types.TypeEngine class in order to provide an alternate _types.TypeEngine.bind_processor() method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.bind_processor(), implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_bind_param().

더 보기

types_typedecorator

매개변수:

dialect – Dialect instance in use.

literal_processor(dialect)

Return a conversion function for processing literal values that are to be rendered directly without using binds.

This function is used when the compiler makes use of the “literal_binds” flag, typically used in DDL generation as well as in certain scenarios where backends don’t accept bound parameters.

Returns a callable which will receive a literal Python value as the sole positional argument and will return a string representation to be rendered in a SQL statement.

참고

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it’s not feasible to subclass a types.TypeEngine class in order to provide an alternate _types.TypeEngine.literal_processor() method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.literal_processor(), implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_literal_param().

더 보기

types_typedecorator

class JSONIndexType

기반 클래스: JSONElementType

Placeholder for the datatype of a JSON index value.

This allows execution-time processing of JSON index values for special syntaxes.

class JSONIntIndexType

기반 클래스: JSONIndexType

Placeholder for the datatype of a JSON index value.

This allows execution-time processing of JSON index values for special syntaxes.

class JSONStrIndexType

기반 클래스: JSONIndexType

Placeholder for the datatype of a JSON index value.

This allows execution-time processing of JSON index values for special syntaxes.

class JSONPathType

기반 클래스: JSONElementType

Placeholder type for JSON path operations.

This allows execution-time processing of a path-based index value into a specific SQL syntax.

class Comparator(expr: ColumnElement[_CT])

기반 클래스: Comparator[_T], Comparator[_T]

Define comparison operations for _types.JSON.

as_boolean()

Consider an indexed value as boolean.

This is similar to using _sql.type_coerce, and will usually not apply a CAST().

e.g.:

stmt = select(mytable.c.json_column["some_data"].as_boolean()).where(
    mytable.c.json_column["some_data"].as_boolean() == True
)

Added in version 1.3.11.

as_string()

Consider an indexed value as string.

This is similar to using _sql.type_coerce, and will usually not apply a CAST().

e.g.:

stmt = select(mytable.c.json_column["some_data"].as_string()).where(
    mytable.c.json_column["some_data"].as_string() == "some string"
)

Added in version 1.3.11.

as_integer()

Consider an indexed value as integer.

This is similar to using _sql.type_coerce, and will usually not apply a CAST().

e.g.:

stmt = select(mytable.c.json_column["some_data"].as_integer()).where(
    mytable.c.json_column["some_data"].as_integer() == 5
)

Added in version 1.3.11.

as_float()

Consider an indexed value as float.

This is similar to using _sql.type_coerce, and will usually not apply a CAST().

e.g.:

stmt = select(mytable.c.json_column["some_data"].as_float()).where(
    mytable.c.json_column["some_data"].as_float() == 29.75
)

Added in version 1.3.11.

as_numeric(precision, scale, asdecimal=True)

Consider an indexed value as numeric/decimal.

This is similar to using _sql.type_coerce, and will usually not apply a CAST().

e.g.:

stmt = select(mytable.c.json_column["some_data"].as_numeric(10, 6)).where(
    mytable.c.json_column["some_data"].as_numeric(10, 6) == 29.75
)

Added in version 1.4.0b2.

as_json()

Consider an indexed value as JSON.

This is similar to using _sql.type_coerce, and will usually not apply a CAST().

e.g.:

stmt = select(mytable.c.json_column["some_data"].as_json())

This is typically the default behavior of indexed elements in any case.

Note that comparison of full JSON structures may not be supported by all backends.

Added in version 1.3.11.

comparator_factory

:py:class:`~sqlalchemy.sql.sqltypes.JSON.Comparator`의 별칭

property python_type

Return the Python type object expected to be returned by instances of this type, if known.

Basically, for those types which enforce a return type, or are known across the board to do such for all common DBAPIs (like int for example), will return that type.

If a return type is not defined, raises NotImplementedError.

Note that any type also accommodates NULL in SQL which means you can also get back None from any type in practice.

property should_evaluate_none

Alias of _types.JSON.none_as_null

bind_processor(dialect)

Return a conversion function for processing bind values.

Returns a callable which will receive a bind parameter value as the sole positional argument and will return a value to send to the DB-API.

If processing is not necessary, the method should return None.

참고

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it’s not feasible to subclass a types.TypeEngine class in order to provide an alternate _types.TypeEngine.bind_processor() method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.bind_processor(), implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_bind_param().

더 보기

types_typedecorator

매개변수:

dialect – Dialect instance in use.

result_processor(dialect, coltype)

Return a conversion function for processing result row values.

Returns a callable which will receive a result row column value as the sole positional argument and will return a value to return to the user.

If processing is not necessary, the method should return None.

참고

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it’s not feasible to subclass a types.TypeEngine class in order to provide an alternate _types.TypeEngine.result_processor() method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.result_processor(), implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_result_value().

더 보기

types_typedecorator

매개변수:
  • dialect – Dialect instance in use.

  • coltype – DBAPI coltype argument received in cursor.description.

class server_modules.AuthRouter(app: DevfiveAPI, *args: Any, **kwargs: Any)

기반 클래스: APIRouter

유저 인증 라우터.

__init__(app: DevfiveAPI, *args: Any, **kwargs: Any) None

유저 인증 라우터.

매개변수:

auth_router_option – 옵션

class server_modules.Boolean(create_constraint: bool = False, name: str | None = None, _create_events: bool = True, _adapted_from: SchemaType | None = None)

기반 클래스: SchemaType, Emulated, TypeEngine

A bool datatype.

Boolean typically uses BOOLEAN or SMALLINT on the DDL side, and on the Python side deals in True or False.

The Boolean datatype currently has two levels of assertion that the values persisted are simple true/false values. For all backends, only the Python values None, True, False, 1 or 0 are accepted as parameter values. For those backends that don’t support a “native boolean” datatype, an option exists to also create a CHECK constraint on the target column

버전 1.2에서 변경: the Boolean datatype now asserts that incoming Python values are already in pure boolean form.

__init__(create_constraint: bool = False, name: str | None = None, _create_events: bool = True, _adapted_from: SchemaType | None = None)

Construct a Boolean.

매개변수:
  • create_constraint

    defaults to False. If the boolean is generated as an int/smallint, also create a CHECK constraint on the table that ensures 1 or 0 as a value.

    참고

    it is strongly recommended that the CHECK constraint have an explicit name in order to support schema-management concerns. This can be established either by setting the :paramref:`.Boolean.name` parameter or by setting up an appropriate naming convention; see constraint_naming_conventions for background.

    버전 1.4에서 변경: - this flag now defaults to False, meaning no CHECK constraint is generated for a non-native enumerated type.

  • name – if a CHECK constraint is generated, specify the name of the constraint.

property python_type

Return the Python type object expected to be returned by instances of this type, if known.

Basically, for those types which enforce a return type, or are known across the board to do such for all common DBAPIs (like int for example), will return that type.

If a return type is not defined, raises NotImplementedError.

Note that any type also accommodates NULL in SQL which means you can also get back None from any type in practice.

literal_processor(dialect)

Return a conversion function for processing literal values that are to be rendered directly without using binds.

This function is used when the compiler makes use of the “literal_binds” flag, typically used in DDL generation as well as in certain scenarios where backends don’t accept bound parameters.

Returns a callable which will receive a literal Python value as the sole positional argument and will return a string representation to be rendered in a SQL statement.

참고

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it’s not feasible to subclass a types.TypeEngine class in order to provide an alternate _types.TypeEngine.literal_processor() method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.literal_processor(), implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_literal_param().

더 보기

types_typedecorator

bind_processor(dialect)

Return a conversion function for processing bind values.

Returns a callable which will receive a bind parameter value as the sole positional argument and will return a value to send to the DB-API.

If processing is not necessary, the method should return None.

참고

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it’s not feasible to subclass a types.TypeEngine class in order to provide an alternate _types.TypeEngine.bind_processor() method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.bind_processor(), implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_bind_param().

더 보기

types_typedecorator

매개변수:

dialect – Dialect instance in use.

result_processor(dialect, coltype)

Return a conversion function for processing result row values.

Returns a callable which will receive a result row column value as the sole positional argument and will return a value to return to the user.

If processing is not necessary, the method should return None.

참고

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it’s not feasible to subclass a types.TypeEngine class in order to provide an alternate _types.TypeEngine.result_processor() method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.result_processor(), implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_result_value().

더 보기

types_typedecorator

매개변수:
  • dialect – Dialect instance in use.

  • coltype – DBAPI coltype argument received in cursor.description.

class server_modules.CrudRouter(db_model: type[M], *, dependencies: Iterable[Depends] | Depends | None = None, prefix: str = '', default_query: DefaultQuery = Ellipsis, get_default_query: DefaultQuery | None = Ellipsis, list_default_query: DefaultQuery | None = Ellipsis, one_default_query: DefaultQuery | None = Ellipsis, create_default_body: CREATE_DEFAULT_BODY | None = Ellipsis, update_default_query: DefaultQuery | None = Ellipsis, patch_default_query: DefaultQuery | None = Ellipsis, delete_default_query: DefaultQuery | None = Ellipsis, api_name: str | None = None, tags: Iterable[str] | None = None, update_scope: str | None = Ellipsis, patch_scope: str | None = Ellipsis, response_scope: str | None = Ellipsis, get_response_scope: str | None = Ellipsis, list_response_scope: str | None = Ellipsis, one_response_scope: str | None = Ellipsis, create_response_scope: str | None = Ellipsis, update_response_scope: str | None = Ellipsis, patch_response_scope: str | None = Ellipsis, auth: IterableOrSingle[str | bool | None] = Ellipsis, get_auth: IterableOrSingle[str | bool | None] = Ellipsis, list_auth: IterableOrSingle[str | bool | None] = Ellipsis, one_auth: IterableOrSingle[str | bool | None] = Ellipsis, create_auth: IterableOrSingle[str | bool | None] = Ellipsis, update_auth: IterableOrSingle[str | bool | None] = Ellipsis, patch_auth: IterableOrSingle[str | bool | None] = Ellipsis, delete_auth: IterableOrSingle[str | bool | None] = Ellipsis, response_omit: Iterable[str] | None = Ellipsis, get_response_omit: Iterable[str] | None = Ellipsis, list_response_omit: Iterable[str] | None = Ellipsis, one_response_omit: Iterable[str] | None = Ellipsis, create_response_omit: Iterable[str] | None = Ellipsis, update_response_omit: Iterable[str] | None = Ellipsis, patch_response_omit: Iterable[str] | None = Ellipsis, update_omit: Iterable[str] | None = Ellipsis, patch_omit: Iterable[str] | None = Ellipsis, update_pick: Iterable[str] | None = Ellipsis, patch_pick: Iterable[str] | None = Ellipsis, response_pick: Iterable[str] | None = Ellipsis, get_response_pick: Iterable[str] | None = Ellipsis, list_response_pick: Iterable[str] | None = Ellipsis, one_response_pick: Iterable[str] | None = Ellipsis, create_response_pick: Iterable[str] | None = Ellipsis, update_response_pick: Iterable[str] | None = Ellipsis, patch_response_pick: Iterable[str] | None = Ellipsis, size: int = 20, pick_route: CRUDRouteType | Iterable[CRUDRouteType] = None, list_route: bool | Iterable[Depends] = True, one_route: bool | Iterable[Depends] = True, create_route: bool | Iterable[Depends] = True, update_route: bool | Iterable[Depends] = True, patch_route: bool | Iterable[Depends] = Ellipsis, delete_route: bool | Iterable[Depends] = True, response_convert_schema: type[S] | None = None, get_response_convert_schema: type[S] | None = None, list_response_convert_schema: type[S] | None = None, one_response_convert_schema: type[S] | None = None, create_response_convert_schema: type[S] | None = None, update_response_convert_schema: type[S] | None = None, patch_response_convert_schema: type[S] | None = None, ignore_deleted_at: Sequence[str | bool] | bool | str | None = Ellipsis, item_key: str | None = None, item_keyword: str = 'item_id', one_comment: str = 'Get One', list_comment: str = 'Get All', create_comment: str = 'Create', update_comment: str = 'Update', patch_comment: str = 'Patch', delete_comment: str = 'Delete', response_convert: Callable[[Request, M], Model] = Ellipsis, get_response_convert: Callable[[Request, M], Model] = Ellipsis, list_response_convert: Callable[[Request, M], Model] = Ellipsis, one_response_convert: Callable[[Request, M], Model] = Ellipsis, create_response_convert: Callable[[Request, M], Model] = Ellipsis, update_response_convert: Callable[[Request, M], Model] = Ellipsis, patch_response_convert: Callable[[Request, M], Model] = Ellipsis, list_before_callback: IterableOrSingle[Callable[[Request, str], RETURN_NONE] | Callable[[Request], RETURN_NONE] | Callable[[], RETURN_NONE]] = None, list_after_callback: IterableOrSingle[Callable[[Request, Iterable[M]], RETURN_NONE] | Callable[[Request], RETURN_NONE] | Callable[[], RETURN_NONE]] = None, list_default_sort: Iterable[str] | str = Ellipsis, one_before_callback: IterableOrSingle[Callable[[Request], RETURN_NONE] | Callable[[], RETURN_NONE]] = None, one_after_callback: IterableOrSingle[Callable[[Request, M], RETURN_NONE] | Callable[[Request], RETURN_NONE] | Callable[[], RETURN_NONE]] = None, create_start_callback: CALLBACK[M] = None, create_before_callback: CALLBACK[M] = None, create_after_callback: CALLBACK[M] = None, update_start_callback: CALLBACK[M] = None, update_before_callback: CALLBACK[M] = None, update_after_callback: CALLBACK[M] = None, patch_start_callback: CALLBACK[M] = None, patch_before_callback: CALLBACK[M] = None, patch_after_callback: CALLBACK[M] = None, delete_start_callback: IterableOrSingle[Callable[[Request, M], RETURN_NONE], Callable[[Request], RETURN_NONE] | Callable[[], RETURN_NONE]] = None, delete_before_callback: IterableOrSingle[Callable[[Request, M], RETURN_NONE], Callable[[Request], RETURN_NONE] | Callable[[], RETURN_NONE]] = None, delete_after_callback: IterableOrSingle[Callable[[Request, M], RETURN_NONE] | Callable[[Request], RETURN_NONE] | Callable[[], RETURN_NONE]] = None, deny_columns: Iterable[str] | None = None, excel: ExcelOption[M] = Ellipsis)

기반 클래스: BaseRouter, Generic

CRUD Router.

__init__(db_model: type[M], *, dependencies: Iterable[Depends] | Depends | None = None, prefix: str = '', default_query: DefaultQuery = Ellipsis, get_default_query: DefaultQuery | None = Ellipsis, list_default_query: DefaultQuery | None = Ellipsis, one_default_query: DefaultQuery | None = Ellipsis, create_default_body: CREATE_DEFAULT_BODY | None = Ellipsis, update_default_query: DefaultQuery | None = Ellipsis, patch_default_query: DefaultQuery | None = Ellipsis, delete_default_query: DefaultQuery | None = Ellipsis, api_name: str | None = None, tags: Iterable[str] | None = None, update_scope: str | None = Ellipsis, patch_scope: str | None = Ellipsis, response_scope: str | None = Ellipsis, get_response_scope: str | None = Ellipsis, list_response_scope: str | None = Ellipsis, one_response_scope: str | None = Ellipsis, create_response_scope: str | None = Ellipsis, update_response_scope: str | None = Ellipsis, patch_response_scope: str | None = Ellipsis, auth: IterableOrSingle[str | bool | None] = Ellipsis, get_auth: IterableOrSingle[str | bool | None] = Ellipsis, list_auth: IterableOrSingle[str | bool | None] = Ellipsis, one_auth: IterableOrSingle[str | bool | None] = Ellipsis, create_auth: IterableOrSingle[str | bool | None] = Ellipsis, update_auth: IterableOrSingle[str | bool | None] = Ellipsis, patch_auth: IterableOrSingle[str | bool | None] = Ellipsis, delete_auth: IterableOrSingle[str | bool | None] = Ellipsis, response_omit: Iterable[str] | None = Ellipsis, get_response_omit: Iterable[str] | None = Ellipsis, list_response_omit: Iterable[str] | None = Ellipsis, one_response_omit: Iterable[str] | None = Ellipsis, create_response_omit: Iterable[str] | None = Ellipsis, update_response_omit: Iterable[str] | None = Ellipsis, patch_response_omit: Iterable[str] | None = Ellipsis, update_omit: Iterable[str] | None = Ellipsis, patch_omit: Iterable[str] | None = Ellipsis, update_pick: Iterable[str] | None = Ellipsis, patch_pick: Iterable[str] | None = Ellipsis, response_pick: Iterable[str] | None = Ellipsis, get_response_pick: Iterable[str] | None = Ellipsis, list_response_pick: Iterable[str] | None = Ellipsis, one_response_pick: Iterable[str] | None = Ellipsis, create_response_pick: Iterable[str] | None = Ellipsis, update_response_pick: Iterable[str] | None = Ellipsis, patch_response_pick: Iterable[str] | None = Ellipsis, size: int = 20, pick_route: CRUDRouteType | Iterable[CRUDRouteType] = None, list_route: bool | Iterable[Depends] = True, one_route: bool | Iterable[Depends] = True, create_route: bool | Iterable[Depends] = True, update_route: bool | Iterable[Depends] = True, patch_route: bool | Iterable[Depends] = Ellipsis, delete_route: bool | Iterable[Depends] = True, response_convert_schema: type[S] | None = None, get_response_convert_schema: type[S] | None = None, list_response_convert_schema: type[S] | None = None, one_response_convert_schema: type[S] | None = None, create_response_convert_schema: type[S] | None = None, update_response_convert_schema: type[S] | None = None, patch_response_convert_schema: type[S] | None = None, ignore_deleted_at: Sequence[str | bool] | bool | str | None = Ellipsis, item_key: str | None = None, item_keyword: str = 'item_id', one_comment: str = 'Get One', list_comment: str = 'Get All', create_comment: str = 'Create', update_comment: str = 'Update', patch_comment: str = 'Patch', delete_comment: str = 'Delete', response_convert: Callable[[Request, M], Model] = Ellipsis, get_response_convert: Callable[[Request, M], Model] = Ellipsis, list_response_convert: Callable[[Request, M], Model] = Ellipsis, one_response_convert: Callable[[Request, M], Model] = Ellipsis, create_response_convert: Callable[[Request, M], Model] = Ellipsis, update_response_convert: Callable[[Request, M], Model] = Ellipsis, patch_response_convert: Callable[[Request, M], Model] = Ellipsis, list_before_callback: IterableOrSingle[Callable[[Request, str], RETURN_NONE] | Callable[[Request], RETURN_NONE] | Callable[[], RETURN_NONE]] = None, list_after_callback: IterableOrSingle[Callable[[Request, Iterable[M]], RETURN_NONE] | Callable[[Request], RETURN_NONE] | Callable[[], RETURN_NONE]] = None, list_default_sort: Iterable[str] | str = Ellipsis, one_before_callback: IterableOrSingle[Callable[[Request], RETURN_NONE] | Callable[[], RETURN_NONE]] = None, one_after_callback: IterableOrSingle[Callable[[Request, M], RETURN_NONE] | Callable[[Request], RETURN_NONE] | Callable[[], RETURN_NONE]] = None, create_start_callback: CALLBACK[M] = None, create_before_callback: CALLBACK[M] = None, create_after_callback: CALLBACK[M] = None, update_start_callback: CALLBACK[M] = None, update_before_callback: CALLBACK[M] = None, update_after_callback: CALLBACK[M] = None, patch_start_callback: CALLBACK[M] = None, patch_before_callback: CALLBACK[M] = None, patch_after_callback: CALLBACK[M] = None, delete_start_callback: IterableOrSingle[Callable[[Request, M], RETURN_NONE], Callable[[Request], RETURN_NONE] | Callable[[], RETURN_NONE]] = None, delete_before_callback: IterableOrSingle[Callable[[Request, M], RETURN_NONE], Callable[[Request], RETURN_NONE] | Callable[[], RETURN_NONE]] = None, delete_after_callback: IterableOrSingle[Callable[[Request, M], RETURN_NONE] | Callable[[Request], RETURN_NONE] | Callable[[], RETURN_NONE]] = None, deny_columns: Iterable[str] | None = None, excel: ExcelOption[M] = Ellipsis) None

CRUD Router.

init(prefix: str) Self

Init 실제로 라우터를 등록한다.

_delete_one(*_: Any, **__: Any) Callable[[Request, str, Model | None], Awaitable[ResultResponse[bool]]]

Delete One Item.

add_route_callback(callback_type: CallbackType, callback: IterableOrSingle[Callable[[Request, M], RETURN_NONE] | Callable[[Request], RETURN_NONE] | Callable[[], RETURN_NONE]]) Self

라우트 콜백을 등록합니다.

매개변수:
  • callback_type – 콜백 타입

  • callback – 콜백 함수

반환:

self

class server_modules.CustomRouter(api_name: str, *args: Any, **kwargs: Any)

기반 클래스: BaseRouter

DevfiveRouter.

__init__(api_name: str, *args: Any, **kwargs: Any) None

Api 라우터.

add_api_route(*args: Any, **kwargs: Any) None

Api 라우터 기본 설정.

get(*args: Any, auth: Sequence[str | bool] | bool | str | None = None, **kwargs: Any) Callable[[DecoratedCallable], DecoratedCallable]

Get method.

post(*args: Any, auth: Sequence[str] | bool | str | None = None, **kwargs: Any) Callable[[DecoratedCallable], DecoratedCallable]

Post method.

put(*args: Any, auth: Sequence[str] | bool | str | None = None, **kwargs: Any) Callable[[DecoratedCallable], DecoratedCallable]

Put method.

patch(*args: Any, auth: Sequence[str] | bool | str | None = None, **kwargs: Any) Callable[[DecoratedCallable], DecoratedCallable]

Patch method.

delete(*args: Any, auth: Sequence[str] | bool | str | None = None, **kwargs: Any) Callable[[DecoratedCallable], DecoratedCallable]

Delete method.

class server_modules.Date

기반 클래스: _RenderISO8601NoT, HasExpressionLookup, TypeEngine

A type for datetime.date() objects.

get_dbapi_type(dbapi)

Return the corresponding type object from the underlying DB-API, if any.

This can be useful for calling setinputsizes(), for example.

property python_type

Return the Python type object expected to be returned by instances of this type, if known.

Basically, for those types which enforce a return type, or are known across the board to do such for all common DBAPIs (like int for example), will return that type.

If a return type is not defined, raises NotImplementedError.

Note that any type also accommodates NULL in SQL which means you can also get back None from any type in practice.

literal_processor(dialect)

Return a conversion function for processing literal values that are to be rendered directly without using binds.

This function is used when the compiler makes use of the “literal_binds” flag, typically used in DDL generation as well as in certain scenarios where backends don’t accept bound parameters.

Returns a callable which will receive a literal Python value as the sole positional argument and will return a string representation to be rendered in a SQL statement.

참고

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it’s not feasible to subclass a types.TypeEngine class in order to provide an alternate _types.TypeEngine.literal_processor() method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.literal_processor(), implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_literal_param().

더 보기

types_typedecorator

class server_modules.DateTime(timezone: bool = False)

기반 클래스: _RenderISO8601NoT, HasExpressionLookup, TypeEngine

A type for datetime.datetime() objects.

Date and time types return objects from the Python datetime module. Most DBAPIs have built in support for the datetime module, with the noted exception of SQLite. In the case of SQLite, date and time types are stored as strings which are then converted back to datetime objects when rows are returned.

For the time representation within the datetime type, some backends include additional options, such as timezone support and fractional seconds support. For fractional seconds, use the dialect-specific datatype, such as mysql.TIME. For timezone support, use at least the _types.TIMESTAMP datatype, if not the dialect-specific datatype object.

__init__(timezone: bool = False)

Construct a new DateTime.

매개변수:

timezone – boolean. Indicates that the datetime type should enable timezone support, if available on the base date/time-holding type only. It is recommended to make use of the _types.TIMESTAMP datatype directly when using this flag, as some databases include separate generic date/time-holding types distinct from the timezone-capable TIMESTAMP datatype, such as Oracle Database.

get_dbapi_type(dbapi)

Return the corresponding type object from the underlying DB-API, if any.

This can be useful for calling setinputsizes(), for example.

literal_processor(dialect)

Return a conversion function for processing literal values that are to be rendered directly without using binds.

This function is used when the compiler makes use of the “literal_binds” flag, typically used in DDL generation as well as in certain scenarios where backends don’t accept bound parameters.

Returns a callable which will receive a literal Python value as the sole positional argument and will return a string representation to be rendered in a SQL statement.

참고

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it’s not feasible to subclass a types.TypeEngine class in order to provide an alternate _types.TypeEngine.literal_processor() method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.literal_processor(), implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_literal_param().

더 보기

types_typedecorator

property python_type

Return the Python type object expected to be returned by instances of this type, if known.

Basically, for those types which enforce a return type, or are known across the board to do such for all common DBAPIs (like int for example), will return that type.

If a return type is not defined, raises NotImplementedError.

Note that any type also accommodates NULL in SQL which means you can also get back None from any type in practice.

class server_modules.Decimal(value='0', context=None)

기반 클래스: object

Construct a new Decimal object. ‘value’ can be an integer, string, tuple, or another Decimal object. If no value is given, return Decimal(‘0’). The context does not affect the conversion and is only passed to determine if the InvalidOperation trap is active.

adjusted()

Return the adjusted exponent of the number. Defined as exp + digits - 1.

as_integer_ratio()

Return a pair of integers, whose ratio is exactly equal to the original Decimal and with a positive denominator. The ratio is in lowest terms. Raise OverflowError on infinities and a ValueError on NaNs.

as_tuple()

Return a tuple representation of the number.

canonical()

Return the canonical encoding of the argument. Currently, the encoding of a Decimal instance is always canonical, so this operation returns its argument unchanged.

compare(other, context=None)

Compare self to other. Return a decimal value:

a or b is a NaN ==> Decimal(‘NaN’) a < b ==> Decimal(‘-1’) a == b ==> Decimal(‘0’) a > b ==> Decimal(‘1’)

compare_signal(other, context=None)

Identical to compare, except that all NaNs signal.

compare_total(other, context=None)

Compare two operands using their abstract representation rather than their numerical value. Similar to the compare() method, but the result gives a total ordering on Decimal instances. Two Decimal instances with the same numeric value but different representations compare unequal in this ordering:

>>> Decimal('12.0').compare_total(Decimal('12'))
Decimal('-1')

Quiet and signaling NaNs are also included in the total ordering. The result of this function is Decimal(‘0’) if both operands have the same representation, Decimal(‘-1’) if the first operand is lower in the total order than the second, and Decimal(‘1’) if the first operand is higher in the total order than the second operand. See the specification for details of the total order.

This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.

compare_total_mag(other, context=None)

Compare two operands using their abstract representation rather than their value as in compare_total(), but ignoring the sign of each operand.

x.compare_total_mag(y) is equivalent to x.copy_abs().compare_total(y.copy_abs()).

This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.

conjugate()

Return self.

copy_abs()

Return the absolute value of the argument. This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed.

copy_negate()

Return the negation of the argument. This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed.

copy_sign(other, context=None)

Return a copy of the first operand with the sign set to be the same as the sign of the second operand. For example:

>>> Decimal('2.3').copy_sign(Decimal('-1.5'))
Decimal('-2.3')

This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.

exp(context=None)

Return the value of the (natural) exponential function e**x at the given number. The function always uses the ROUND_HALF_EVEN mode and the result is correctly rounded.

fma(other, third, context=None)

Fused multiply-add. Return self*other+third with no rounding of the intermediate product self*other.

>>> Decimal(2).fma(3, 5)
Decimal('11')
classmethod from_float(f, /)

Class method that converts a float to a decimal number, exactly. Since 0.1 is not exactly representable in binary floating point, Decimal.from_float(0.1) is not the same as Decimal(‘0.1’).

>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal.from_float(float('nan'))
Decimal('NaN')
>>> Decimal.from_float(float('inf'))
Decimal('Infinity')
>>> Decimal.from_float(float('-inf'))
Decimal('-Infinity')
is_canonical()

Return True if the argument is canonical and False otherwise. Currently, a Decimal instance is always canonical, so this operation always returns True.

is_finite()

Return True if the argument is a finite number, and False if the argument is infinite or a NaN.

is_infinite()

Return True if the argument is either positive or negative infinity and False otherwise.

is_nan()

Return True if the argument is a (quiet or signaling) NaN and False otherwise.

is_normal(context=None)

Return True if the argument is a normal finite non-zero number with an adjusted exponent greater than or equal to Emin. Return False if the argument is zero, subnormal, infinite or a NaN.

is_qnan()

Return True if the argument is a quiet NaN, and False otherwise.

is_signed()

Return True if the argument has a negative sign and False otherwise. Note that both zeros and NaNs can carry signs.

is_snan()

Return True if the argument is a signaling NaN and False otherwise.

is_subnormal(context=None)

Return True if the argument is subnormal, and False otherwise. A number is subnormal if it is non-zero, finite, and has an adjusted exponent less than Emin.

is_zero()

Return True if the argument is a (positive or negative) zero and False otherwise.

ln(context=None)

Return the natural (base e) logarithm of the operand. The function always uses the ROUND_HALF_EVEN mode and the result is correctly rounded.

log10(context=None)

Return the base ten logarithm of the operand. The function always uses the ROUND_HALF_EVEN mode and the result is correctly rounded.

logb(context=None)

For a non-zero number, return the adjusted exponent of the operand as a Decimal instance. If the operand is a zero, then Decimal(‘-Infinity’) is returned and the DivisionByZero condition is raised. If the operand is an infinity then Decimal(‘Infinity’) is returned.

logical_and(other, context=None)

Return the digit-wise ‘and’ of the two (logical) operands.

logical_invert(context=None)

Return the digit-wise inversion of the (logical) operand.

logical_or(other, context=None)

Return the digit-wise ‘or’ of the two (logical) operands.

logical_xor(other, context=None)

Return the digit-wise ‘exclusive or’ of the two (logical) operands.

max(other, context=None)

Maximum of self and other. If one operand is a quiet NaN and the other is numeric, the numeric operand is returned.

max_mag(other, context=None)

Similar to the max() method, but the comparison is done using the absolute values of the operands.

min(other, context=None)

Minimum of self and other. If one operand is a quiet NaN and the other is numeric, the numeric operand is returned.

min_mag(other, context=None)

Similar to the min() method, but the comparison is done using the absolute values of the operands.

next_minus(context=None)

Return the largest number representable in the given context (or in the current default context if no context is given) that is smaller than the given operand.

next_plus(context=None)

Return the smallest number representable in the given context (or in the current default context if no context is given) that is larger than the given operand.

next_toward(other, context=None)

If the two operands are unequal, return the number closest to the first operand in the direction of the second operand. If both operands are numerically equal, return a copy of the first operand with the sign set to be the same as the sign of the second operand.

normalize(context=None)

Normalize the number by stripping the rightmost trailing zeros and converting any result equal to Decimal(‘0’) to Decimal(‘0e0’). Used for producing canonical values for members of an equivalence class. For example, Decimal(‘32.100’) and Decimal(‘0.321000e+2’) both normalize to the equivalent value Decimal(‘32.1’).

number_class(context=None)

Return a string describing the class of the operand. The returned value is one of the following ten strings:

  • ‘-Infinity’, indicating that the operand is negative infinity.

  • ‘-Normal’, indicating that the operand is a negative normal number.

  • ‘-Subnormal’, indicating that the operand is negative and subnormal.

  • ‘-Zero’, indicating that the operand is a negative zero.

  • ‘+Zero’, indicating that the operand is a positive zero.

  • ‘+Subnormal’, indicating that the operand is positive and subnormal.

  • ‘+Normal’, indicating that the operand is a positive normal number.

  • ‘+Infinity’, indicating that the operand is positive infinity.

  • ‘NaN’, indicating that the operand is a quiet NaN (Not a Number).

  • ‘sNaN’, indicating that the operand is a signaling NaN.

quantize(exp, rounding=None, context=None)

Return a value equal to the first operand after rounding and having the exponent of the second operand.

>>> Decimal('1.41421356').quantize(Decimal('1.000'))
Decimal('1.414')

Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision, then an InvalidOperation is signaled. This guarantees that, unless there is an error condition, the quantized exponent is always equal to that of the right-hand operand.

Also unlike other operations, quantize never signals Underflow, even if the result is subnormal and inexact.

If the exponent of the second operand is larger than that of the first, then rounding may be necessary. In this case, the rounding mode is determined by the rounding argument if given, else by the given context argument; if neither argument is given, the rounding mode of the current thread’s context is used.

radix()

Return Decimal(10), the radix (base) in which the Decimal class does all its arithmetic. Included for compatibility with the specification.

remainder_near(other, context=None)

Return the remainder from dividing self by other. This differs from self % other in that the sign of the remainder is chosen so as to minimize its absolute value. More precisely, the return value is self - n * other where n is the integer nearest to the exact value of self / other, and if two integers are equally near then the even one is chosen.

If the result is zero then its sign will be the sign of self.

rotate(other, context=None)

Return the result of rotating the digits of the first operand by an amount specified by the second operand. The second operand must be an integer in the range -precision through precision. The absolute value of the second operand gives the number of places to rotate. If the second operand is positive then rotation is to the left; otherwise rotation is to the right. The coefficient of the first operand is padded on the left with zeros to length precision if necessary. The sign and exponent of the first operand are unchanged.

same_quantum(other, context=None)

Test whether self and other have the same exponent or whether both are NaN.

This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.

scaleb(other, context=None)

Return the first operand with the exponent adjusted the second. Equivalently, return the first operand multiplied by 10**other. The second operand must be an integer.

shift(other, context=None)

Return the result of shifting the digits of the first operand by an amount specified by the second operand. The second operand must be an integer in the range -precision through precision. The absolute value of the second operand gives the number of places to shift. If the second operand is positive, then the shift is to the left; otherwise the shift is to the right. Digits shifted into the coefficient are zeros. The sign and exponent of the first operand are unchanged.

sqrt(context=None)

Return the square root of the argument to full precision. The result is correctly rounded using the ROUND_HALF_EVEN rounding mode.

to_eng_string(context=None)

Convert to an engineering-type string. Engineering notation has an exponent which is a multiple of 3, so there are up to 3 digits left of the decimal place. For example, Decimal(‘123E+1’) is converted to Decimal(‘1.23E+3’).

The value of context.capitals determines whether the exponent sign is lower or upper case. Otherwise, the context does not affect the operation.

to_integral(rounding=None, context=None)

Identical to the to_integral_value() method. The to_integral() name has been kept for compatibility with older versions.

to_integral_exact(rounding=None, context=None)

Round to the nearest integer, signaling Inexact or Rounded as appropriate if rounding occurs. The rounding mode is determined by the rounding parameter if given, else by the given context. If neither parameter is given, then the rounding mode of the current default context is used.

to_integral_value(rounding=None, context=None)

Round to the nearest integer without signaling Inexact or Rounded. The rounding mode is determined by the rounding parameter if given, else by the given context. If neither parameter is given, then the rounding mode of the current default context is used.

class server_modules.DeletedTimeModel

기반 클래스: object

db에서 직접 삭제를 하면 안되는 테이블에서 사용되는 Column.

server_modules.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            ')] = 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            ')] = True) 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 server_modules.DevfiveAPI(*, name: str = 'devup-server', title: str = 'DevfiveAPI', description: str = '', version: str = '0.1.0', prod_origins: Iterable[str] | None = None, auth: AuthRouterOption | None = None, file_router: FileRouterOption | Literal[True] | Iterable[FileRouterOption] | None = None, internal_server_error_callback: Callable[[Request], Any] | None = None, root_path: str | None = None, on_startup: Callable[[Self], Coroutine[Any, Any, None] | None] | None = None, on_shutdown: Callable[[Self], Coroutine[Any, Any, None] | None] | None = None, **extra: Any)

기반 클래스: FastAPI

DevfiveAPI.

__init__(*, name: str = 'devup-server', title: str = 'DevfiveAPI', description: str = '', version: str = '0.1.0', prod_origins: Iterable[str] | None = None, auth: AuthRouterOption | None = None, file_router: FileRouterOption | Literal[True] | Iterable[FileRouterOption] | None = None, internal_server_error_callback: Callable[[Request], Any] | None = None, root_path: str | None = None, on_startup: Callable[[Self], Coroutine[Any, Any, None] | None] | None = None, on_shutdown: Callable[[Self], Coroutine[Any, Any, None] | None] | None = None, **extra: Any) None

DevfiveAPI.

데브파이브 API를 생성합니다.

include_router(router: T, *args: Any, **kwargs: Any) None

Include a router.

add_model(model: type[Model]) None

Add model.

class server_modules.ExpiredTimeModel

기반 클래스: object

만기 시점을 일러주는 Column.

server_modules.Field(default: ellipsis, *, alias: str | None = _Unset, alias_priority: int | None = _Unset, validation_alias: str | AliasPath | AliasChoices | None = _Unset, serialization_alias: str | None = _Unset, title: str | None = _Unset, field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, description: str | None = _Unset, examples: list[Any] | None = _Unset, exclude: bool | None = _Unset, discriminator: str | Discriminator | None = _Unset, deprecated: deprecated | str | bool | None = _Unset, json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, frozen: bool | None = _Unset, validate_default: bool | None = _Unset, repr: bool = _Unset, init: bool | None = _Unset, init_var: bool | None = _Unset, kw_only: bool | None = _Unset, pattern: str | Pattern[str] | None = _Unset, strict: bool | None = _Unset, coerce_numbers_to_str: bool | None = _Unset, gt: SupportsGt | None = _Unset, ge: SupportsGe | None = _Unset, lt: SupportsLt | None = _Unset, le: SupportsLe | None = _Unset, multiple_of: float | None = _Unset, allow_inf_nan: bool | None = _Unset, max_digits: int | None = _Unset, decimal_places: int | None = _Unset, min_length: int | None = _Unset, max_length: int | None = _Unset, union_mode: Literal['smart', 'left_to_right'] = _Unset, fail_fast: bool | None = _Unset, **extra: Unpack[_EmptyKwargs]) Any
server_modules.Field(default: _T, *, alias: str | None = _Unset, alias_priority: int | None = _Unset, validation_alias: str | AliasPath | AliasChoices | None = _Unset, serialization_alias: str | None = _Unset, title: str | None = _Unset, field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, description: str | None = _Unset, examples: list[Any] | None = _Unset, exclude: bool | None = _Unset, discriminator: str | Discriminator | None = _Unset, deprecated: deprecated | str | bool | None = _Unset, json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, frozen: bool | None = _Unset, validate_default: bool | None = _Unset, repr: bool = _Unset, init: bool | None = _Unset, init_var: bool | None = _Unset, kw_only: bool | None = _Unset, pattern: str | Pattern[str] | None = _Unset, strict: bool | None = _Unset, coerce_numbers_to_str: bool | None = _Unset, gt: SupportsGt | None = _Unset, ge: SupportsGe | None = _Unset, lt: SupportsLt | None = _Unset, le: SupportsLe | None = _Unset, multiple_of: float | None = _Unset, allow_inf_nan: bool | None = _Unset, max_digits: int | None = _Unset, decimal_places: int | None = _Unset, min_length: int | None = _Unset, max_length: int | None = _Unset, union_mode: Literal['smart', 'left_to_right'] = _Unset, fail_fast: bool | None = _Unset, **extra: Unpack[_EmptyKwargs]) _T
server_modules.Field(*, default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T], alias: str | None = _Unset, alias_priority: int | None = _Unset, validation_alias: str | AliasPath | AliasChoices | None = _Unset, serialization_alias: str | None = _Unset, title: str | None = _Unset, field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, description: str | None = _Unset, examples: list[Any] | None = _Unset, exclude: bool | None = _Unset, discriminator: str | Discriminator | None = _Unset, deprecated: deprecated | str | bool | None = _Unset, json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, frozen: bool | None = _Unset, validate_default: bool | None = _Unset, repr: bool = _Unset, init: bool | None = _Unset, init_var: bool | None = _Unset, kw_only: bool | None = _Unset, pattern: str | Pattern[str] | None = _Unset, strict: bool | None = _Unset, coerce_numbers_to_str: bool | None = _Unset, gt: SupportsGt | None = _Unset, ge: SupportsGe | None = _Unset, lt: SupportsLt | None = _Unset, le: SupportsLe | None = _Unset, multiple_of: float | None = _Unset, allow_inf_nan: bool | None = _Unset, max_digits: int | None = _Unset, decimal_places: int | None = _Unset, min_length: int | None = _Unset, max_length: int | None = _Unset, union_mode: Literal['smart', 'left_to_right'] = _Unset, fail_fast: bool | None = _Unset, **extra: Unpack[_EmptyKwargs]) _T
server_modules.Field(*, alias: str | None = _Unset, alias_priority: int | None = _Unset, validation_alias: str | AliasPath | AliasChoices | None = _Unset, serialization_alias: str | None = _Unset, title: str | None = _Unset, field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, description: str | None = _Unset, examples: list[Any] | None = _Unset, exclude: bool | None = _Unset, discriminator: str | Discriminator | None = _Unset, deprecated: deprecated | str | bool | None = _Unset, json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, frozen: bool | None = _Unset, validate_default: bool | None = _Unset, repr: bool = _Unset, init: bool | None = _Unset, init_var: bool | None = _Unset, kw_only: bool | None = _Unset, pattern: str | Pattern[str] | None = _Unset, strict: bool | None = _Unset, coerce_numbers_to_str: bool | None = _Unset, gt: SupportsGt | None = _Unset, ge: SupportsGe | None = _Unset, lt: SupportsLt | None = _Unset, le: SupportsLe | None = _Unset, multiple_of: float | None = _Unset, allow_inf_nan: bool | None = _Unset, max_digits: int | None = _Unset, decimal_places: int | None = _Unset, min_length: int | None = _Unset, max_length: int | None = _Unset, union_mode: Literal['smart', 'left_to_right'] = _Unset, fail_fast: bool | None = _Unset, **extra: Unpack[_EmptyKwargs]) Any
!!! abstract “Usage Documentation”

[Fields](../concepts/fields.md)

Create a field for objects that can be configured.

Used to provide extra information about a field, either for the model schema or complex validation. Some arguments apply only to number fields (int, float, Decimal) and some apply only to str.

참고

  • Any _Unset objects will be replaced by the corresponding value defined in the _DefaultValues dictionary. If a key for the _Unset object is not found in the _DefaultValues dictionary, it will default to None

매개변수:
  • default – Default value if the field is not set.

  • default_factory – A callable to generate the default value. The callable can either take 0 arguments (in which case it is called as is) or a single argument containing the already validated data.

  • alias – The name to use for the attribute when validating or serializing by alias. This is often used for things like converting between snake and camel case.

  • alias_priority – Priority of the alias. This affects whether an alias generator is used.

  • validation_alias – Like alias, but only affects validation, not serialization.

  • serialization_alias – Like alias, but only affects serialization, not validation.

  • title – Human-readable title.

  • field_title_generator – A callable that takes a field name and returns title for it.

  • description – Human-readable description.

  • examples – Example values for this field.

  • exclude – Whether to exclude the field from the model serialization.

  • discriminator – Field name or Discriminator for discriminating the type in a tagged union.

  • deprecated – A deprecation message, an instance of warnings.deprecated or the typing_extensions.deprecated backport, or a boolean. If True, a default deprecation message will be emitted when accessing the field.

  • json_schema_extra – A dict or callable to provide extra JSON schema properties.

  • frozen – Whether the field is frozen. If true, attempts to change the value on an instance will raise an error.

  • validate_default – If True, apply validation to the default value every time you create an instance. Otherwise, for performance reasons, the default value of the field is trusted and not validated.

  • repr – A boolean indicating whether to include the field in the __repr__ output.

  • init – Whether the field should be included in the constructor of the dataclass. (Only applies to dataclasses.)

  • init_var – Whether the field should _only_ be included in the constructor of the dataclass. (Only applies to dataclasses.)

  • kw_only – Whether the field should be a keyword-only argument in the constructor of the dataclass. (Only applies to dataclasses.)

  • coerce_numbers_to_str – Whether to enable coercion of any Number type to str (not applicable in strict mode).

  • strict – If True, strict validation is applied to the field. See [Strict Mode](../concepts/strict_mode.md) for details.

  • gt – Greater than. If set, value must be greater than this. Only applicable to numbers.

  • ge – Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers.

  • lt – Less than. If set, value must be less than this. Only applicable to numbers.

  • le – Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers.

  • multiple_of – Value must be a multiple of this. Only applicable to numbers.

  • min_length – Minimum length for iterables.

  • max_length – Maximum length for iterables.

  • pattern – Pattern for strings (a regular expression).

  • allow_inf_nan – Allow inf, -inf, nan. Only applicable to float and [Decimal][decimal.Decimal] numbers.

  • max_digits – Maximum number of allow digits for strings.

  • decimal_places – Maximum number of decimal places allowed for numbers.

  • union_mode – The strategy to apply when validating a union. Can be smart (the default), or left_to_right. See [Union Mode](../concepts/unions.md#union-modes) for details.

  • fail_fast – If True, validation will stop on the first error. If False, all validation errors will be collected. This option can be applied only to iterable types (list, tuple, set, and frozenset).

  • extra

    (Deprecated) Extra fields that will be included in the JSON schema.

    !!! warning Deprecated

    The extra kwargs is deprecated. Use json_schema_extra instead.

반환:

A new [FieldInfo][pydantic.fields.FieldInfo]. The return annotation is Any so Field can be used on

type-annotated fields without causing a type error.

class server_modules.FileRouter(**option: Unpack[FileRouterOption])

기반 클래스: APIRouter

파일 업로드 관련 라우터.

__init__(**option: Unpack[FileRouterOption]) None
매개변수:

option – FileRouterOption

class server_modules.Float(precision: int | None = ..., asdecimal: Literal[False] = ..., decimal_return_scale: int | None = ...)
class server_modules.Float(precision: int | None = ..., asdecimal: Literal[True] = ..., decimal_return_scale: int | None = ...)

기반 클래스: Numeric

Type representing floating point types, such as FLOAT or REAL.

This type returns Python float objects by default, unless the :paramref:`.Float.asdecimal` flag is set to True, in which case they are coerced to decimal.Decimal objects.

When a :paramref:`.Float.precision` is not provided in a _types.Float type some backend may compile this type as an 8 bytes / 64 bit float datatype. To use a 4 bytes / 32 bit float datatype a precision <= 24 can usually be provided or the _types.REAL type can be used. This is known to be the case in the PostgreSQL and MSSQL dialects that render the type as FLOAT that’s in both an alias of DOUBLE PRECISION. Other third party dialects may have similar behavior.

__init__(precision: int | None = None, asdecimal: Literal[False] = False, decimal_return_scale: int | None = None)
__init__(precision: int | None = None, asdecimal: Literal[True] = False, decimal_return_scale: int | None = None)

Construct a Float.

매개변수:
  • precision

    the numeric precision for use in DDL CREATE TABLE. Backends should attempt to ensure this precision indicates a number of digits for the generic _sqltypes.Float datatype.

    참고

    For the Oracle Database backend, the :paramref:`_sqltypes.Float.precision` parameter is not accepted when rendering DDL, as Oracle Database does not support float precision specified as a number of decimal places. Instead, use the Oracle Database-specific _oracle.FLOAT datatype and specify the :paramref:`_oracle.FLOAT.binary_precision` parameter. This is new in version 2.0 of SQLAlchemy.

    To create a database agnostic _types.Float that separately specifies binary precision for Oracle Database, use _types.TypeEngine.with_variant() as follows:

    from sqlalchemy import Column
    from sqlalchemy import Float
    from sqlalchemy.dialects import oracle
    
    Column(
        "float_data",
        Float(5).with_variant(oracle.FLOAT(binary_precision=16), "oracle"),
    )
    

  • asdecimal – the same flag as that of Numeric, but defaults to False. Note that setting this flag to True results in floating point conversion.

  • decimal_return_scale – Default scale to use when converting from floats to Python decimals. Floating point values will typically be much longer due to decimal inaccuracy, and most floating point database types don’t have a notion of “scale”, so by default the float type looks for the first ten decimal places when converting. Specifying this value will override that length. Note that the MySQL float types, which do include “scale”, will use “scale” as the default for decimal_return_scale, if not otherwise specified.

result_processor(dialect, coltype)

Return a conversion function for processing result row values.

Returns a callable which will receive a result row column value as the sole positional argument and will return a value to return to the user.

If processing is not necessary, the method should return None.

참고

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it’s not feasible to subclass a types.TypeEngine class in order to provide an alternate _types.TypeEngine.result_processor() method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.result_processor(), implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_result_value().

더 보기

types_typedecorator

매개변수:
  • dialect – Dialect instance in use.

  • coltype – DBAPI coltype argument received in cursor.description.

class server_modules.ForeignKey(column: _DDLColumnArgument, _constraint: ForeignKeyConstraint | None = None, use_alter: bool = False, name: _ConstraintNameArgument = None, onupdate: str | None = None, ondelete: str | None = None, deferrable: bool | None = None, initially: str | None = None, link_to_name: bool = False, match: str | None = None, info: _InfoType | None = None, comment: str | None = None, _unresolvable: bool = False, **dialect_kw: Any)

기반 클래스: DialectKWArgs, SchemaItem

Defines a dependency between two columns.

ForeignKey is specified as an argument to a _schema.Column object, e.g.:

t = Table(
    "remote_table",
    metadata,
    Column("remote_id", ForeignKey("main_table.id")),
)

Note that ForeignKey is only a marker object that defines a dependency between two columns. The actual constraint is in all cases represented by the _schema.ForeignKeyConstraint object. This object will be generated automatically when a ForeignKey is associated with a _schema.Column which in turn is associated with a _schema.Table. Conversely, when _schema.ForeignKeyConstraint is applied to a _schema.Table, ForeignKey markers are automatically generated to be present on each associated _schema.Column, which are also associated with the constraint object.

Note that you cannot define a “composite” foreign key constraint, that is a constraint between a grouping of multiple parent/child columns, using ForeignKey objects. To define this grouping, the _schema.ForeignKeyConstraint object must be used, and applied to the _schema.Table. The associated ForeignKey objects are created automatically.

The ForeignKey objects associated with an individual _schema.Column object are available in the foreign_keys collection of that column.

Further examples of foreign key configuration are in metadata_foreignkeys.

__init__(column: _DDLColumnArgument, _constraint: ForeignKeyConstraint | None = None, use_alter: bool = False, name: _ConstraintNameArgument = None, onupdate: str | None = None, ondelete: str | None = None, deferrable: bool | None = None, initially: str | None = None, link_to_name: bool = False, match: str | None = None, info: _InfoType | None = None, comment: str | None = None, _unresolvable: bool = False, **dialect_kw: Any)

Construct a column-level FOREIGN KEY.

The _schema.ForeignKey object when constructed generates a _schema.ForeignKeyConstraint which is associated with the parent _schema.Table object’s collection of constraints.

매개변수:
  • column – A single target column for the key relationship. A _schema.Column object or a column name as a string: tablename.columnkey or schema.tablename.columnkey. columnkey is the key which has been assigned to the column (defaults to the column name itself), unless link_to_name is True in which case the rendered name of the column is used.

  • name – Optional string. An in-database name for the key if constraint is not provided.

  • onupdate – Optional string. If set, emit ON UPDATE <value> when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT.

  • ondelete – Optional string. If set, emit ON DELETE <value> when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT.

  • deferrable – Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint.

  • initially – Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint.

  • link_to_name – if True, the string name given in column is the rendered name of the referenced column, not its locally assigned key.

  • use_alter

    passed to the underlying _schema.ForeignKeyConstraint to indicate the constraint should be generated/dropped externally from the CREATE TABLE/ DROP TABLE statement. See :paramref:`_schema.ForeignKeyConstraint.use_alter` for further description.

  • match – Optional string. If set, emit MATCH <value> when issuing DDL for this constraint. Typical values include SIMPLE, PARTIAL and FULL.

  • info – Optional data dictionary which will be populated into the SchemaItem.info attribute of this object.

  • comment

    Optional string that will render an SQL comment on foreign key constraint creation.

    Added in version 2.0.

  • **dialect_kw – Additional keyword arguments are dialect specific, and passed in the form <dialectname>_<argname>. The arguments are ultimately handled by a corresponding _schema.ForeignKeyConstraint. See the documentation regarding an individual dialect at dialect_toplevel for detail on documented arguments.

copy(*, schema: str | None = None, **kw: Any) ForeignKey

버전 1.4부터 폐지됨: The _schema.ForeignKey.copy() method is deprecated and will be removed in a future release.

_copy(*, schema: str | None = None, **kw: Any) ForeignKey

Produce a copy of this _schema.ForeignKey object.

The new _schema.ForeignKey will not be bound to any _schema.Column.

This method is usually used by the internal copy procedures of _schema.Column, _schema.Table, and _schema.MetaData.

매개변수:

schema – The returned _schema.ForeignKey will reference the original table and column name, qualified by the given string schema name.

_get_colspec(schema: str | Literal[SchemaConst.RETAIN_SCHEMA, SchemaConst.BLANK_SCHEMA] | None = None, table_name: str | None = None, _is_copy: bool = False) str

Return a string based ‘column specification’ for this _schema.ForeignKey.

This is usually the equivalent of the string-based “tablename.colname” argument first passed to the object’s constructor.

property target_fullname: str

Return a string based ‘column specification’ for this _schema.ForeignKey.

This is usually the equivalent of the string-based “tablename.colname” argument first passed to the object’s constructor.

references(table: Table) bool

Return True if the given _schema.Table is referenced by this _schema.ForeignKey.

get_referent(table: FromClause) Column[Any] | None

Return the _schema.Column in the given _schema.Table (or any FromClause) referenced by this _schema.ForeignKey.

Returns None if this _schema.ForeignKey does not reference the given _schema.Table.

column

Return the target _schema.Column referenced by this _schema.ForeignKey.

If no target column has been established, an exception is raised.

exception server_modules.HTTPException(code: int, *detail: Any, status_code: int = 400, value: Any | None = None, headers: dict[str, str] | None = None)
exception server_modules.HTTPException(error: str, status_code: int = 400, code: int | None = None, value: Any | None = None, headers: dict[str, str] | None = None)
exception server_modules.HTTPException(*detail: Any, status_code: int = 400, code: int | None = None, value: Any | None = None, headers: dict[str, str] | None = None)

기반 클래스: HTTPException

HTTP 예외 처리를 위한 예외 클래스.

변수:
  • (int) (code)

  • (Any) (value)

__init__(code: int, *detail: Any, status_code: int = 400, value: Any | None = None, headers: dict[str, str] | None = None) None
__init__(error: str, status_code: int = 400, code: int | None = None, value: Any | None = None, headers: dict[str, str] | None = None) None
__init__(*detail: Any, status_code: int = 400, code: int | None = None, value: Any | None = None, headers: dict[str, str] | None = None) None

HTTP 예외 처리를 위한 예외 클래스.

Args:

status_code (int): HTTP 상태 코드 detail (str | list[Any], optional): 예외 상세 정보. Defaults to None. code (int, optional): 예외 코드. Defaults to None. value (Any, optional): 예외 값. Defaults to None. headers (dict[str, str], optional): HTTP 헤더. Defaults to None.

class server_modules.Integer

기반 클래스: HasExpressionLookup, TypeEngine

A type for int integers.

get_dbapi_type(dbapi)

Return the corresponding type object from the underlying DB-API, if any.

This can be useful for calling setinputsizes(), for example.

property python_type

Return the Python type object expected to be returned by instances of this type, if known.

Basically, for those types which enforce a return type, or are known across the board to do such for all common DBAPIs (like int for example), will return that type.

If a return type is not defined, raises NotImplementedError.

Note that any type also accommodates NULL in SQL which means you can also get back None from any type in practice.

literal_processor(dialect)

Return a conversion function for processing literal values that are to be rendered directly without using binds.

This function is used when the compiler makes use of the “literal_binds” flag, typically used in DDL generation as well as in certain scenarios where backends don’t accept bound parameters.

Returns a callable which will receive a literal Python value as the sole positional argument and will return a string representation to be rendered in a SQL statement.

참고

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it’s not feasible to subclass a types.TypeEngine class in order to provide an alternate _types.TypeEngine.literal_processor() method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.literal_processor(), implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_literal_param().

더 보기

types_typedecorator

class server_modules.JsonResultResponse(*, rs: Json)

기반 클래스: Schema

JSON Result schema.

model_config = {'alias_generator': <function to_camel>, 'from_attributes': True, 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class server_modules.Mapped

기반 클래스: SQLORMExpression[_T_co], ORMDescriptor[_T_co], _MappedAnnotationBase[_T_co], DDLConstraintColumnRole

Represent an ORM mapped attribute on a mapped class.

This class represents the complete descriptor interface for any class attribute that will have been instrumented by the ORM _orm.Mapper class. Provides appropriate information to type checkers such as pylance and mypy so that ORM-mapped attributes are correctly typed.

The most prominent use of _orm.Mapped is in the Declarative Mapping form of _orm.Mapper configuration, where used explicitly it drives the configuration of ORM attributes such as _orm.mapped_class() and _orm.relationship().

더 보기

orm_explicit_declarative_base

orm_declarative_table

The _orm.Mapped class represents attributes that are handled directly by the _orm.Mapper class. It does not include other Python descriptor classes that are provided as extensions, including hybrids_toplevel and the associationproxy_toplevel. While these systems still make use of ORM-specific superclasses and structures, they are not instrumented by the _orm.Mapper and instead provide their own functionality when they are accessed on a class.

Added in version 1.4.

class server_modules.Model(**kwargs: Any)

기반 클래스: AsyncAttrs, DeclarativeBase

DB Base Model.

ORM 과 연동하기 위한 최상위 부모 클래스.

metadata = MetaData()

Refers to the _schema.MetaData collection that will be used for new _schema.Table objects.

더 보기

orm_declarative_metadata

classmethod BaseSchema() type[Schema]

기반 스키마를 반환합니다.

classmethod ListSchema() type[Schema]

List 스키마를 반환합니다.

classmethod OneSchema() type[Schema]

One 스키마를 반환합니다.

classmethod CreateSchema() type[Schema]

Create 스키마를 반환합니다.

async to_schema(crud_type: Literal['list', 'one', 'create', 'update', 'patch', 'base'] = 'one') Schema

모델을 스키마로 변환합니다.

async delete(*, commit: bool = True) None

모델을 삭제합니다.

async save(*, commit: bool = True) None

모델을 저장합니다.

classmethod UpdateSchema() type[Schema]

Update 스키마를 반환합니다.

classmethod PatchSchema() type[Schema]

Patch 스키마를 반환합니다.

async classmethod query_get(**kwargs: Unpack[type[Self]]) Self | None
async classmethod query_get(value: Any, column: str | None = None) Self | None

model_id로 해당 모델을 가져옴, deleted_at 영향을 받지 않음.

매개변수:
  • value

  • column

반환:

async classmethod query_has(**kwargs: Unpack[type[Self]]) bool
async classmethod query_has(value: Any, column: str | None = None) bool

model_id로 해당 델의 존재 여부를 반환, deleted_at 영향을 받지 않음.

매개변수:
  • value

  • column

반환:

async classmethod query_get_with_error(**kwargs: Unpack[type[Self]]) Self
async classmethod query_get_with_error(value: Any, column: str | None = None) Self

model_id로 해당 모델을 가져옴, deleted_at 영향을 받지 않음.

매개변수:
  • value

  • column

반환:

async classmethod query(query: str, *, page: int = 1, size: int = 20, sort: str = '') PaginationResponse[Self]

query로 해당 모델을 가져옴.

async classmethod query_first(query: str = '', sort: str = '') Self

query로 첫번째 모델을 가져옵니다.

async classmethod query_first_with_error(query: str, *, sort: str = '') Self

query로 첫번째 모델을 가져옴.

반환:

classmethod model_name() str

Model name.

반환:

__init__(**kwargs: Any) None

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

classmethod get_pk(*, immutable: bool = False) Sequence[ColumnElement]

Get immutable pk.

반환:

registry = <sqlalchemy.orm.decl_api.registry object>

Refers to the _orm.registry in use where new _orm.Mapper objects will be associated.

classmethod get_column_or_pk() Sequence[ColumnElement]
classmethod get_column_or_pk(column_name: str) ColumnElement

모델에서 컬럼을 반환합니다. 만약 칼럼이 없다면 pk 칼럼을 반환합니다.

classmethod get_crud_schema(crud_type: Literal['list', 'one', 'create', 'update', 'patch', 'base']) type[Schema]

Get Schema.

반환:

classmethod body_type() Literal['json', 'form']

Get body type.

classmethod __init_subclass__(*args: Any, **kwargs: Any) None

기본 타입 설정.

classmethod _register_special_type(key: str, target_annotation: TypeAlias) None

특수 타입을 등록합니다.

class server_modules.PaginationResponse(*, total: int, items: Sequence)

기반 클래스: Schema, Generic

PaginationResponse Schema.

변수:
  • total (Total Count)

  • items (Result)

classmethod __init_subclass__(**kwargs: Any) None

PaginationResponse.

devup 에 포함되지 않도록 설정합니다.

model_config = {'alias_generator': <function to_camel>, 'from_attributes': True, 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class server_modules.PasswordType(max_length=None, **kwargs)

기반 클래스: ScalarCoercible, TypeDecorator

PasswordType hashes passwords as they come into the database and allows verifying them using a Pythonic interface. This Pythonic interface relies on setting up automatic data type coercion using the force_auto_coercion() function.

All keyword arguments (aside from max_length) are forwarded to the construction of a passlib.context.LazyCryptContext object, which also supports deferred configuration via the onload callback.

The following usage will create a password column that will automatically hash new passwords as pbkdf2_sha512 but still compare passwords against pre-existing md5_crypt hashes. As passwords are compared; the password hash in the database will be updated to be pbkdf2_sha512.

class Model(Base):
    password = sa.Column(PasswordType(
        schemes=[
            'pbkdf2_sha512',
            'md5_crypt'
        ],

        deprecated=['md5_crypt']
    ))

Verifying password is as easy as:

target = Model()
target.password = 'b'
# '$5$rounds=80000$H.............'

target.password == 'b'
# True

Lazy configuration of the type with Flask config:

import flask
from sqlalchemy_utils import PasswordType, force_auto_coercion

force_auto_coercion()

class User(db.Model):
    __tablename__ = 'user'

    password = db.Column(
        PasswordType(
            # The returned dictionary is forwarded to the CryptContext
            onload=lambda **kwargs: dict(
                schemes=flask.current_app.config['PASSWORD_SCHEMES'],
                **kwargs
            ),
        ),
        unique=False,
        nullable=False,
    )
cache_ok = True

Indicate if statements using this ExternalType are “safe to cache”.

The default value None will emit a warning and then not allow caching of a statement which includes this type. Set to False to disable statements using this type from being cached at all without a warning. When set to True, the object’s class and selected elements from its state will be used as part of the cache key. For example, using a TypeDecorator:

class MyType(TypeDecorator):
    impl = String

    cache_ok = True

    def __init__(self, choices):
        self.choices = tuple(choices)
        self.internal_only = True

The cache key for the above type would be equivalent to:

>>> MyType(["a", "b", "c"])._static_cache_key
(<class '__main__.MyType'>, ('choices', ('a', 'b', 'c')))

The caching scheme will extract attributes from the type that correspond to the names of parameters in the __init__() method. Above, the “choices” attribute becomes part of the cache key but “internal_only” does not, because there is no parameter named “internal_only”.

The requirements for cacheable elements is that they are hashable and also that they indicate the same SQL rendered for expressions using this type every time for a given cache value.

To accommodate for datatypes that refer to unhashable structures such as dictionaries, sets and lists, these objects can be made “cacheable” by assigning hashable structures to the attributes whose names correspond with the names of the arguments. For example, a datatype which accepts a dictionary of lookup values may publish this as a sorted series of tuples. Given a previously un-cacheable type as:

class LookupType(UserDefinedType):
    """a custom type that accepts a dictionary as a parameter.

    this is the non-cacheable version, as "self.lookup" is not
    hashable.

    """

    def __init__(self, lookup):
        self.lookup = lookup

    def get_col_spec(self, **kw):
        return "VARCHAR(255)"

    def bind_processor(self, dialect): ...  # works with "self.lookup" ...

Where “lookup” is a dictionary. The type will not be able to generate a cache key:

>>> type_ = LookupType({"a": 10, "b": 20})
>>> type_._static_cache_key
<stdin>:1: SAWarning: UserDefinedType LookupType({'a': 10, 'b': 20}) will not
produce a cache key because the ``cache_ok`` flag is not set to True.
Set this flag to True if this type object's state is safe to use
in a cache key, or False to disable this warning.
symbol('no_cache')

If we did set up such a cache key, it wouldn’t be usable. We would get a tuple structure that contains a dictionary inside of it, which cannot itself be used as a key in a “cache dictionary” such as SQLAlchemy’s statement cache, since Python dictionaries aren’t hashable:

>>> # set cache_ok = True
>>> type_.cache_ok = True

>>> # this is the cache key it would generate
>>> key = type_._static_cache_key
>>> key
(<class '__main__.LookupType'>, ('lookup', {'a': 10, 'b': 20}))

>>> # however this key is not hashable, will fail when used with
>>> # SQLAlchemy statement cache
>>> some_cache = {key: "some sql value"}
Traceback (most recent call last): File "<stdin>", line 1,
in <module> TypeError: unhashable type: 'dict'

The type may be made cacheable by assigning a sorted tuple of tuples to the “.lookup” attribute:

class LookupType(UserDefinedType):
    """a custom type that accepts a dictionary as a parameter.

    The dictionary is stored both as itself in a private variable,
    and published in a public variable as a sorted tuple of tuples,
    which is hashable and will also return the same value for any
    two equivalent dictionaries.  Note it assumes the keys and
    values of the dictionary are themselves hashable.

    """

    cache_ok = True

    def __init__(self, lookup):
        self._lookup = lookup

        # assume keys/values of "lookup" are hashable; otherwise
        # they would also need to be converted in some way here
        self.lookup = tuple((key, lookup[key]) for key in sorted(lookup))

    def get_col_spec(self, **kw):
        return "VARCHAR(255)"

    def bind_processor(self, dialect): ...  # works with "self._lookup" ...

Where above, the cache key for LookupType({"a": 10, "b": 20}) will be:

>>> LookupType({"a": 10, "b": 20})._static_cache_key
(<class '__main__.LookupType'>, ('lookup', (('a', 10), ('b', 20))))

Added in version 1.4.14: - added the cache_ok flag to allow some configurability of caching for TypeDecorator classes.

Added in version 1.4.28: - added the ExternalType mixin which generalizes the cache_ok flag to both the TypeDecorator and UserDefinedType classes.

더 보기

sql_caching

__init__(max_length=None, **kwargs)
property length

Get column length.

load_dialect_impl(dialect)

Return a TypeEngine object corresponding to a dialect.

This is an end-user override hook that can be used to provide differing types depending on the given dialect. It is used by the TypeDecorator implementation of type_engine() to help determine what type should ultimately be returned for a given TypeDecorator.

By default returns self.impl.

process_bind_param(value, dialect)

Receive a bound parameter value to be converted.

Custom subclasses of _types.TypeDecorator should override this method to provide custom behaviors for incoming data values. This method is called at statement execution time and is passed the literal Python data value which is to be associated with a bound parameter in the statement.

The operation could be anything desired to perform custom behavior, such as transforming or serializing data. This could also be used as a hook for validating logic.

매개변수:
  • value – Data to operate upon, of any type expected by this method in the subclass. Can be None.

  • dialect – the Dialect in use.

더 보기

types_typedecorator

_types.TypeDecorator.process_result_value()

process_result_value(value, dialect)

Receive a result-row column value to be converted.

Custom subclasses of _types.TypeDecorator should override this method to provide custom behaviors for data values being received in result rows coming from the database. This method is called at result fetching time and is passed the literal Python data value that’s extracted from a database result row.

The operation could be anything desired to perform custom behavior, such as transforming or deserializing data.

매개변수:
  • value – Data to operate upon, of any type expected by this method in the subclass. Can be None.

  • dialect – the Dialect in use.

더 보기

types_typedecorator

_types.TypeDecorator.process_bind_param()

property python_type

Return the Python type object expected to be returned by instances of this type, if known.

Basically, for those types which enforce a return type, or are known across the board to do such for all common DBAPIs (like int for example), will return that type.

If a return type is not defined, raises NotImplementedError.

Note that any type also accommodates NULL in SQL which means you can also get back None from any type in practice.

class server_modules.ProxyRouter(api_name: str, target_url: str, *, username: str | None = None, password: str | None = None, signin_url: str = '/signin', auth_header: str = 'Authorization', timeout: int = 10, app: DevfiveAPI | None = None, dependencies: Sequence[Depends] | None = None, **kwargs: Any)

기반 클래스: BaseRouter

proxy routers.

__init__(api_name: str, target_url: str, *, username: str | None = None, password: str | None = None, signin_url: str = '/signin', auth_header: str = 'Authorization', timeout: int = 10, app: DevfiveAPI | None = None, dependencies: Sequence[Depends] | None = None, **kwargs: Any) None

Proxy routers.

exception server_modules.QueryError(*detail: Any)

기반 클래스: Exception

Query 예외 처리를 위한 예외 클래스.

일반적으로 HTTPException 으로 변환되어서 반환됩니다.

__init__(*detail: Any) None

Query 예외 처리를 위한 예외 클래스.

Args:

detail (str | list[Any], optional): 예외 상세 정보. Defaults to None.

class server_modules.Request(scope: ~typing.MutableMapping[str, ~typing.Any], receive: ~typing.Callable[[], ~typing.Awaitable[~typing.MutableMapping[str, ~typing.Any]]] = <function empty_receive>, send: ~typing.Callable[[~typing.MutableMapping[str, ~typing.Any]], ~typing.Awaitable[None]] = <function empty_send>)

기반 클래스: HTTPConnection

__init__(scope: ~typing.MutableMapping[str, ~typing.Any], receive: ~typing.Callable[[], ~typing.Awaitable[~typing.MutableMapping[str, ~typing.Any]]] = <function empty_receive>, send: ~typing.Callable[[~typing.MutableMapping[str, ~typing.Any]], ~typing.Awaitable[None]] = <function empty_send>)
class server_modules.ResultResponse(rs: T)

기반 클래스: Schema, Generic

Result schema.

__init__(rs: T, **kwargs: Any) None

ResultResponse Schema.

classmethod __init_subclass__(**kwargs: Any) None

PaginationResponse Schema.

devup 에 포함되지 않도록 설정합니다.

model_config = {'alias_generator': <function to_camel>, 'from_attributes': True, 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class server_modules.Schema

기반 클래스: BaseModel

Schema.

model_config = {'alias_generator': <function to_camel>, 'from_attributes': True, 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

classmethod create_model(_schema: type[Self], **kwargs: Any) type[Self]

Create model.

classmethod __init_subclass__(schema_type: Literal['crud', 'crud_reform', 'internal'] | None = None, body_type: Literal['json', 'form'] = 'json', async_schema_fields: Iterable[str] | None = None, hybrid_function: Iterable[str] | None = None, orm_map: dict[str, type[Model]] | None = None, **kwargs: Any) None

Async field 를 등록합니다.

async classmethod async_model_validate(data: Any) Self

Async model validate.

static to_py_dict(schema: type[Schema], data: Any) Any

to_py_dict. formdata에서 json을 받기 위하여 개선.

classmethod validator(data: Any) Any

to_py_dict. formdata에서 json을 받기 위하여 개선.

convert_to_orm() tuple[dict[str, Any], Iterable[Model] | None]

스키마의 내부 필드를 ORM으로 변환합니다.

nested create 를 구현하기 위함입니다.

class server_modules.SigninResponse(*, accessToken: str, refreshToken: str, tokenType: str, accessTokenExpireAt: str, refreshTokenExpireAt: str, root: bool | None = False, model: str | None = None)

기반 클래스: Schema

JWT Signin Response.

model_config = {'alias_generator': <function to_camel>, 'from_attributes': True, 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class server_modules.SingletonRouter(db_model: type[M], default_data: dict[str, Any], *, dependencies: Iterable[Depends] | None = None, prefix: str = '', api_name: str | None = None, tags: Iterable[str] | None = None, auth: Iterable[str | bool | None] | str | bool | None = Ellipsis, get_auth: Iterable[str | bool | None] | str | bool | None = Ellipsis, update_auth: Iterable[str | bool | None] | str | bool | None = Ellipsis, patch_auth: Iterable[str | bool | None] | str | bool | None = Ellipsis, delete_auth: Iterable[str | bool | None] | str | bool | None = Ellipsis, response_omit: Iterable[str] | None = Ellipsis, get_response_omit: Iterable[str] | None = Ellipsis, update_response_omit: Iterable[str] | None = Ellipsis, patch_response_omit: Iterable[str] | None = Ellipsis, delete_response_omit: Iterable[str] | None = Ellipsis, update_omit: Iterable[str] | None = Ellipsis, patch_omit: Iterable[str] | None = Ellipsis, update_pick: Iterable[str] | None = Ellipsis, patch_pick: Iterable[str] | None = Ellipsis, response_pick: Iterable[str] | None = Ellipsis, get_response_pick: Iterable[str] | None = Ellipsis, update_response_pick: Iterable[str] | None = Ellipsis, patch_response_pick: Iterable[str] | None = Ellipsis, delete_response_pick: Iterable[str] | None = Ellipsis, pick_route: Literal['get', 'update', 'delete', 'patch'] | Iterable[Literal['get', 'update', 'delete', 'patch']] = None, get_route: bool | Iterable[Depends] = True, update_route: bool | Iterable[Depends] = True, patch_route: bool | Iterable[Depends] = True, delete_route: bool | Iterable[Depends] = True, response_convert_schema: type[S] | None = None, get_response_convert_schema: type[S] | None = None, update_response_convert_schema: type[S] | None = None, patch_response_convert_schema: type[S] | None = None, delete_response_convert_schema: type[S] | None = None, get_comment: str = 'Get', update_comment: str = 'Update', patch_comment: str = 'Patch', delete_comment: str = 'Delete', response_convert: Callable[[Request, M], Model] = Ellipsis, get_response_convert: Callable[[Request, M], Model] = Ellipsis, update_response_convert: Callable[[Request, M], Model] = Ellipsis, patch_response_convert: Callable[[Request, M], Model] = Ellipsis, get_before_callback: IterableOrSingle[Callable[[Request], RETURN_NONE], Callable[[], RETURN_NONE]] | None = None, get_after_callback: IterableOrSingle[Callable[[Request, Iterable[M]], RETURN_NONE], Callable[[Request], RETURN_NONE], Callable[[], RETURN_NONE]] | None = None, update_start_callback: CALLBACK[M] = None, update_before_callback: CALLBACK[M] = None, update_after_callback: CALLBACK[M] = None, patch_start_callback: CALLBACK[M] = None, patch_before_callback: CALLBACK[M] = None, patch_after_callback: CALLBACK[M] = None, delete_before_callback: IterableOrSingle[Callable[[Request, M], RETURN_NONE], Callable[[Request], RETURN_NONE], Callable[[], RETURN_NONE]] | None = None, delete_after_callback: IterableOrSingle[Callable[[Request, M], RETURN_NONE], Callable[[Request], RETURN_NONE], Callable[[], RETURN_NONE]] | None = None)

기반 클래스: BaseRouter, Generic

filter 추가 Router.

__init__(db_model: type[M], default_data: dict[str, Any], *, dependencies: Iterable[Depends] | None = None, prefix: str = '', api_name: str | None = None, tags: Iterable[str] | None = None, auth: Iterable[str | bool | None] | str | bool | None = Ellipsis, get_auth: Iterable[str | bool | None] | str | bool | None = Ellipsis, update_auth: Iterable[str | bool | None] | str | bool | None = Ellipsis, patch_auth: Iterable[str | bool | None] | str | bool | None = Ellipsis, delete_auth: Iterable[str | bool | None] | str | bool | None = Ellipsis, response_omit: Iterable[str] | None = Ellipsis, get_response_omit: Iterable[str] | None = Ellipsis, update_response_omit: Iterable[str] | None = Ellipsis, patch_response_omit: Iterable[str] | None = Ellipsis, delete_response_omit: Iterable[str] | None = Ellipsis, update_omit: Iterable[str] | None = Ellipsis, patch_omit: Iterable[str] | None = Ellipsis, update_pick: Iterable[str] | None = Ellipsis, patch_pick: Iterable[str] | None = Ellipsis, response_pick: Iterable[str] | None = Ellipsis, get_response_pick: Iterable[str] | None = Ellipsis, update_response_pick: Iterable[str] | None = Ellipsis, patch_response_pick: Iterable[str] | None = Ellipsis, delete_response_pick: Iterable[str] | None = Ellipsis, pick_route: Literal['get', 'update', 'delete', 'patch'] | Iterable[Literal['get', 'update', 'delete', 'patch']] = None, get_route: bool | Iterable[Depends] = True, update_route: bool | Iterable[Depends] = True, patch_route: bool | Iterable[Depends] = True, delete_route: bool | Iterable[Depends] = True, response_convert_schema: type[S] | None = None, get_response_convert_schema: type[S] | None = None, update_response_convert_schema: type[S] | None = None, patch_response_convert_schema: type[S] | None = None, delete_response_convert_schema: type[S] | None = None, get_comment: str = 'Get', update_comment: str = 'Update', patch_comment: str = 'Patch', delete_comment: str = 'Delete', response_convert: Callable[[Request, M], Model] = Ellipsis, get_response_convert: Callable[[Request, M], Model] = Ellipsis, update_response_convert: Callable[[Request, M], Model] = Ellipsis, patch_response_convert: Callable[[Request, M], Model] = Ellipsis, get_before_callback: IterableOrSingle[Callable[[Request], RETURN_NONE], Callable[[], RETURN_NONE]] | None = None, get_after_callback: IterableOrSingle[Callable[[Request, Iterable[M]], RETURN_NONE], Callable[[Request], RETURN_NONE], Callable[[], RETURN_NONE]] | None = None, update_start_callback: CALLBACK[M] = None, update_before_callback: CALLBACK[M] = None, update_after_callback: CALLBACK[M] = None, patch_start_callback: CALLBACK[M] = None, patch_before_callback: CALLBACK[M] = None, patch_after_callback: CALLBACK[M] = None, delete_before_callback: IterableOrSingle[Callable[[Request, M], RETURN_NONE], Callable[[Request], RETURN_NONE], Callable[[], RETURN_NONE]] | None = None, delete_after_callback: IterableOrSingle[Callable[[Request, M], RETURN_NONE], Callable[[Request], RETURN_NONE], Callable[[], RETURN_NONE]] | None = None) None

Singleton Router.

init(prefix: str) Self

Init 실제로 라우터를 등록한다.

_delete_one(*_: Any, **__: Any) Callable[[Request, Model | None], Awaitable[dict[str, Any]]]

Delete One Item.

add_route_callback(callback_type: Literal['get_before', 'get_after', 'update_start', 'update_before', 'update_after', 'patch_start', 'patch_before', 'patch_after', 'delete_before', 'delete_after'], callback: CALLBACK[M]) Self

라우트 콜백을 등록합니다.

매개변수:
  • callback_type – 콜백 타입

  • callback – 콜백 함수

반환:

self

class server_modules.String(length: int | None = None, collation: str | None = None)

기반 클래스: Concatenable, TypeEngine

The base for all string and character types.

In SQL, corresponds to VARCHAR.

The length field is usually required when the String type is used within a CREATE TABLE statement, as VARCHAR requires a length on most databases.

__init__(length: int | None = None, collation: str | None = None)

Create a string-holding type.

매개변수:
  • length – optional, a length for the column for use in DDL and CAST expressions. May be safely omitted if no CREATE TABLE will be issued. Certain databases may require a length for use in DDL, and will raise an exception when the CREATE TABLE DDL is issued if a VARCHAR with no length is included. Whether the value is interpreted as bytes or characters is database specific.

  • collation

    Optional, a column-level collation for use in DDL and CAST expressions. Renders using the COLLATE keyword supported by SQLite, MySQL, and PostgreSQL. E.g.:

    >>> from sqlalchemy import cast, select, String
    >>> print(select(cast("some string", String(collation="utf8"))))
    {printsql}SELECT CAST(:param_1 AS VARCHAR COLLATE utf8) AS anon_1
    

    참고

    In most cases, the Unicode or UnicodeText datatypes should be used for a _schema.Column that expects to store non-ascii data. These datatypes will ensure that the correct types are used on the database.

literal_processor(dialect)

Return a conversion function for processing literal values that are to be rendered directly without using binds.

This function is used when the compiler makes use of the “literal_binds” flag, typically used in DDL generation as well as in certain scenarios where backends don’t accept bound parameters.

Returns a callable which will receive a literal Python value as the sole positional argument and will return a string representation to be rendered in a SQL statement.

참고

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it’s not feasible to subclass a types.TypeEngine class in order to provide an alternate _types.TypeEngine.literal_processor() method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.literal_processor(), implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_literal_param().

더 보기

types_typedecorator

bind_processor(dialect)

Return a conversion function for processing bind values.

Returns a callable which will receive a bind parameter value as the sole positional argument and will return a value to send to the DB-API.

If processing is not necessary, the method should return None.

참고

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it’s not feasible to subclass a types.TypeEngine class in order to provide an alternate _types.TypeEngine.bind_processor() method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.bind_processor(), implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_bind_param().

더 보기

types_typedecorator

매개변수:

dialect – Dialect instance in use.

result_processor(dialect, coltype)

Return a conversion function for processing result row values.

Returns a callable which will receive a result row column value as the sole positional argument and will return a value to return to the user.

If processing is not necessary, the method should return None.

참고

This method is only called relative to a dialect specific type object, which is often private to a dialect in use and is not the same type object as the public facing one, which means it’s not feasible to subclass a types.TypeEngine class in order to provide an alternate _types.TypeEngine.result_processor() method, unless subclassing the _types.UserDefinedType class explicitly.

To provide alternate behavior for _types.TypeEngine.result_processor(), implement a _types.TypeDecorator class and provide an implementation of _types.TypeDecorator.process_result_value().

더 보기

types_typedecorator

매개변수:
  • dialect – Dialect instance in use.

  • coltype – DBAPI coltype argument received in cursor.description.

property python_type

Return the Python type object expected to be returned by instances of this type, if known.

Basically, for those types which enforce a return type, or are known across the board to do such for all common DBAPIs (like int for example), will return that type.

If a return type is not defined, raises NotImplementedError.

Note that any type also accommodates NULL in SQL which means you can also get back None from any type in practice.

get_dbapi_type(dbapi)

Return the corresponding type object from the underlying DB-API, if any.

This can be useful for calling setinputsizes(), for example.

class server_modules.TimeModel

기반 클래스: object

모델에 기본적으로 넣어야 하는 시간 Column.

server_modules.check_auth(jwt_token: str | None = Depends(OAuth2PasswordBearer)) bool

JWT가 적용되어 있는지 확인하는 Depend 함수입니다.

매개변수:

jwt_token – JWT 토큰. Defaults to Depends(OAuth2PasswordBearer(“/signin”, “_”)).

server_modules.check_root(jwt_token: str | None = Depends(OAuth2PasswordBearer)) bool

JWT가 ROOT인지 확인, ROOT_USERNAME 환경변수로 설정.

server_modules.check_root_or_none(jwt_token: str | None = Depends(OAuth2PasswordBearer)) bool

JWT가 ROOT인지 확인, ROOT_USERNAME 환경변수로 설정.

async server_modules.check_root_or_user(jwt_token: str | None = Depends(OAuth2PasswordBearer)) bool

Root 혹은 유저인지 확인.

async server_modules.check_user(jwt_token: str | None = Depends(OAuth2PasswordBearer)) bool

유저 확인.

매개변수:

jwt_token – jwt 토큰

class server_modules.comment(comment: str)

기반 클래스: DevfiveColumnType

column 에 comment 를 추가합니다.

__init__(comment: str) None

__init__.

classmethod __class_getitem__(comment: str) Self

See PEP 585.

class server_modules.date

기반 클래스: object

date(year, month, day) –> date object

ctime()

Return ctime() style string.

classmethod fromisocalendar()

int, int, int -> Construct a date from the ISO year, week number and weekday.

This is the inverse of the date.isocalendar() function

classmethod fromisoformat()

str -> Construct a date from a string in ISO 8601 format.

classmethod fromordinal()

int -> date corresponding to a proleptic Gregorian ordinal.

classmethod fromtimestamp(timestamp, /)

Create a date from a POSIX timestamp.

The timestamp is a number, e.g. created via time.time(), that is interpreted as local time.

isocalendar()

Return a named tuple containing ISO year, week number, and weekday.

isoformat()

Return string in ISO 8601 format, YYYY-MM-DD.

isoweekday()

Return the day of the week represented by the date. Monday == 1 … Sunday == 7

replace()

Return date with new specified fields.

strftime()

format -> strftime() style string.

timetuple()

Return time tuple, compatible with time.localtime().

classmethod today()

Current date or datetime: same as self.__class__.fromtimestamp(time.time()).

toordinal()

Return proleptic Gregorian ordinal. January 1 of year 1 is day 1.

weekday()

Return the day of the week represented by the date. Monday == 0 … Sunday == 6

class server_modules.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])

기반 클래스: date

The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints.

astimezone()

tz -> convert to local time in new timezone tz

classmethod combine()

date, time -> datetime with same date and time fields

ctime()

Return ctime() style string.

date()

Return date object with same year, month and day.

dst()

Return self.tzinfo.dst(self).

classmethod fromisoformat()

string -> datetime from a string in most ISO 8601 formats

classmethod fromtimestamp()

timestamp[, tz] -> tz’s local time from POSIX timestamp.

isoformat()

[sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM]. sep is used to separate the year from the time, and defaults to ‘T’. The optional argument timespec specifies the number of additional terms of the time to include. Valid options are ‘auto’, ‘hours’, ‘minutes’, ‘seconds’, ‘milliseconds’ and ‘microseconds’.

classmethod now(tz=None)

Returns new datetime object representing current time local to tz.

tz

Timezone object.

If no tz is specified, uses local timezone.

replace()

Return datetime with new specified fields.

classmethod strptime()

string, format -> new datetime parsed from a string (like time.strptime()).

time()

Return time object with same time but with tzinfo=None.

timestamp()

Return POSIX timestamp as float.

timetuple()

Return time tuple, compatible with time.localtime().

timetz()

Return time object with same time and tzinfo.

tzname()

Return self.tzinfo.tzname(self).

classmethod utcfromtimestamp()

Construct a naive UTC datetime from a POSIX timestamp.

classmethod utcnow()

Return a new datetime representing UTC day and time.

utcoffset()

Return self.tzinfo.utcoffset(self).

utctimetuple()

Return UTC time tuple, compatible with time.localtime().

server_modules.db

:py:class:`~server_modules.middlewares.db_session.create_middleware_and_session_proxy.<locals>.DBSession`의 별칭

server_modules.decode_jwt_token(jwt_token: str) dict

Jwt 확인.

class server_modules.default(default_: Any)

기반 클래스: DevfiveColumnType

column 에 default 를 추가합니다. (server_default 아님).

__init__(default_: Any) None

__init__.

classmethod __class_getitem__(default_: AnyStr | bool | int | type[str] | list | dict) Self

See PEP 585.

class server_modules.excel(title: str | dict[str, str], convert: ExcelConverterArg = None)

기반 클래스: DevfiveColumnType

excel로 출력할 때 excel의 칼럼 제목을 정합니다.

__init__(title: str | dict[str, str], convert: ExcelConverterArg = None) None

__init__.

classmethod __class_getitem__(title: str | dict[str, str] | type[str], convert: ExcelConverterArg = None) Self

See PEP 585.

create_excel_info(title: str) ExcelInfo

ExcelInfo 를 생성합니다.

server_modules.exists(__argument: _ColumnsClauseArgument[Any] | SelectBase | ScalarSelect[Any] | None = None) Exists

Construct a new _expression.Exists construct.

The _sql.exists() can be invoked by itself to produce an _sql.Exists construct, which will accept simple WHERE criteria:

exists_criteria = exists().where(table1.c.col1 == table2.c.col2)

However, for greater flexibility in constructing the SELECT, an existing _sql.Select construct may be converted to an _sql.Exists, most conveniently by making use of the _sql.SelectBase.exists() method:

exists_criteria = (
    select(table2.c.col2).where(table1.c.col1 == table2.c.col2).exists()
)

The EXISTS criteria is then used inside of an enclosing SELECT:

stmt = select(table1.c.col1).where(exists_criteria)

The above statement will then be of the form:

SELECT col1 FROM table1 WHERE EXISTS
(SELECT table2.col2 FROM table2 WHERE table2.col2 = table1.col1)

더 보기

tutorial_exists - in the 2.0 style tutorial.

_sql.SelectBase.exists() - method to transform a SELECT to an EXISTS clause.

server_modules.factory_check_root_or_user(model_name: str, *rest_model_name: str) Callable[[str | None], Coroutine[Any, Any, bool]]

Root 혹은 유저인지 확인.

매개변수:

model_name – 유저 모델 이름

server_modules.factory_check_user(*model_name: AuthFactoryOption) Callable[[str | None], Coroutine[Any, Any, bool]]

유저 확인.

매개변수:

model_name – 유저 모델 이름

server_modules.factory_check_user_field(field: str, value: Callable[[Any], bool] | Any, *model_name: str) Callable[[str | None], Coroutine[Any, Any, bool]]

유저 필드 팩토리.

server_modules.factory_get_user(*model_name: AuthFactoryOption[M] | None) Callable[[str | None], Coroutine[Any, Any, Model | None]]

Get user.

server_modules.firebase(*, cred: str | None | dict = None, session_type: Literal['app'] = 'app') AbstractContextManager[App]
server_modules.firebase(*, cred: str | None | dict = None, session_type: Literal['firestore'] = 'firestore') AbstractContextManager[Client]

Firebase Session.

class server_modules.fk(fk_: AnyStr | type[Model] | type[Column] | DevfiveColumnType | type[DevfiveColumnType])

기반 클래스: DevfiveColumnType

column 에 fk 를 추가합니다.

__init__(fk_: AnyStr | type[Model] | type[Column] | DevfiveColumnType | type[DevfiveColumnType]) None

__init__.

classmethod __class_getitem__(fk_: AnyStr | type[str] | type['Model'] | type['Column'] | DevfiveColumnType | type[DevfiveColumnType]) Self

See PEP 585.

set_fk_column(column: Column) None

Fk 를 설정합니다.

class server_modules.flag(flag_type: Literal['user_available'])

기반 클래스: DevfiveColumnType

여러 flag 칼럼을 생성합니다.

__init__(flag_type: Literal['user_available']) None

__init__.

classmethod __class_getitem__(flag_type: Literal['user_available']) Self

See PEP 585.

property column_type: type

Column type.

async server_modules.get_auth(jwt_token: str = Depends(OAuth2PasswordBearer)) Model

Auth를 반환하는 Depend입니다.

매개변수:

jwt_token – JWT 토큰. Defaults to Depends(OAuth2PasswordBearer(“/signin”, “_”, auto_error=False)).

async server_modules.get_auth_or_none(jwt_token: str | None = Depends(OAuth2PasswordBearer)) Model | None

유저 혹은 None을 반환하는 Depend입니다.

매개변수:

jwt_token – JWT 토큰. Defaults to Depends(OAuth2PasswordBearer(“/signin”, “_”, auto_error=False)).

async server_modules.get_deep_value(data: object, deep_key: str, key_to_snake: bool = False) Any

Deep key를 통해 value를 가져옵니다.

async server_modules.get_user(jwt_token: str | None = Depends(OAuth2PasswordBearer)) Model | None

Jwt 확인.

async server_modules.get_user_by_request(request: Request) T | None

request에서 jwt를 가져와서 확인 후 user를 반환합니다.

매개변수:

request (Request) – FastAPI의 request 객체

async server_modules.get_user_by_request_with_error(request: Request) T

request에서 jwt를 가져와서 확인 후 user를 반환합니다.

매개변수:

request (Request) – FastAPI의 request 객체

class server_modules.hybrid_property(fget: _HybridGetterType[_T], fset: _HybridSetterType[_T] | None = None, fdel: _HybridDeleterType[_T] | None = None, expr: _HybridExprCallableType[_T] | None = None, custom_comparator: Comparator[_T] | None = None, update_expr: _HybridUpdaterType[_T] | None = None)

기반 클래스: InspectionAttrInfo, ORMDescriptor[_T]

A decorator which allows definition of a Python descriptor with both instance-level and class-level behavior.

is_attribute = True

True if this object is a Python descriptor.

This can refer to one of many types. Usually a QueryableAttribute which handles attributes events on behalf of a MapperProperty. But can also be an extension type such as AssociationProxy or hybrid_property. The InspectionAttr.extension_type will refer to a constant identifying the specific subtype.

더 보기

_orm.Mapper.all_orm_descriptors

extension_type: InspectionAttrExtensionType = 'HYBRID_PROPERTY'

The extension type, if any. Defaults to interfaces.NotExtension.NOT_EXTENSION

더 보기

HybridExtensionType

AssociationProxyExtensionType

__init__(fget: _HybridGetterType[_T], fset: _HybridSetterType[_T] | None = None, fdel: _HybridDeleterType[_T] | None = None, expr: _HybridExprCallableType[_T] | None = None, custom_comparator: Comparator[_T] | None = None, update_expr: _HybridUpdaterType[_T] | None = None)

Create a new hybrid_property.

Usage is typically via decorator:

from sqlalchemy.ext.hybrid import hybrid_property


class SomeClass:
    @hybrid_property
    def value(self):
        return self._value

    @value.setter
    def value(self, value):
        self._value = value
property overrides: Self

Prefix for a method that is overriding an existing attribute.

The hybrid_property.overrides accessor just returns this hybrid object, which when called at the class level from a parent class, will de-reference the “instrumented attribute” normally returned at this level, and allow modifying decorators like hybrid_property.expression() and hybrid_property.comparator() to be used without conflicting with the same-named attributes normally present on the QueryableAttribute:

class SuperClass:
    # ...

    @hybrid_property
    def foobar(self):
        return self._foobar


class SubClass(SuperClass):
    # ...

    @SuperClass.foobar.overrides.expression
    def foobar(cls):
        return func.subfoobar(self._foobar)

Added in version 1.2.

더 보기

hybrid_reuse_subclass

property inplace: _InPlace[_T]

Return the inplace mutator for this hybrid_property.

This is to allow in-place mutation of the hybrid, allowing the first hybrid method of a certain name to be re-used in order to add more methods without having to name those methods the same, e.g.:

class Interval(Base):
    # ...

    @hybrid_property
    def radius(self) -> float:
        return abs(self.length) / 2

    @radius.inplace.setter
    def _radius_setter(self, value: float) -> None:
        self.length = value * 2

    @radius.inplace.expression
    def _radius_expression(cls) -> ColumnElement[float]:
        return type_coerce(func.abs(cls.length) / 2, Float)

Added in version 2.0.4.

더 보기

hybrid_pep484_naming

getter(fget: _HybridGetterType[_T]) hybrid_property[_T]

Provide a modifying decorator that defines a getter method.

Added in version 1.2.

setter(fset: _HybridSetterType[_T]) hybrid_property[_T]

Provide a modifying decorator that defines a setter method.

deleter(fdel: _HybridDeleterType[_T]) hybrid_property[_T]

Provide a modifying decorator that defines a deletion method.

expression(expr: _HybridExprCallableType[_T]) hybrid_property[_T]

Provide a modifying decorator that defines a SQL-expression producing method.

When a hybrid is invoked at the class level, the SQL expression given here is wrapped inside of a specialized QueryableAttribute, which is the same kind of object used by the ORM to represent other mapped attributes. The reason for this is so that other class-level attributes such as docstrings and a reference to the hybrid itself may be maintained within the structure that’s returned, without any modifications to the original SQL expression passed in.

참고

When referring to a hybrid property from an owning class (e.g. SomeClass.some_hybrid), an instance of QueryableAttribute is returned, representing the expression or comparator object as well as this hybrid object. However, that object itself has accessors called expression and comparator; so when attempting to override these decorators on a subclass, it may be necessary to qualify it using the hybrid_property.overrides modifier first. See that modifier for details.

더 보기

hybrid_distinct_expression

comparator(comparator: _HybridComparatorCallableType[_T]) hybrid_property[_T]

Provide a modifying decorator that defines a custom comparator producing method.

The return value of the decorated method should be an instance of Comparator.

참고

The hybrid_property.comparator() decorator replaces the use of the hybrid_property.expression() decorator. They cannot be used together.

When a hybrid is invoked at the class level, the Comparator object given here is wrapped inside of a specialized QueryableAttribute, which is the same kind of object used by the ORM to represent other mapped attributes. The reason for this is so that other class-level attributes such as docstrings and a reference to the hybrid itself may be maintained within the structure that’s returned, without any modifications to the original comparator object passed in.

참고

When referring to a hybrid property from an owning class (e.g. SomeClass.some_hybrid), an instance of QueryableAttribute is returned, representing the expression or comparator object as this hybrid object. However, that object itself has accessors called expression and comparator; so when attempting to override these decorators on a subclass, it may be necessary to qualify it using the hybrid_property.overrides modifier first. See that modifier for details.

update_expression(meth: _HybridUpdaterType[_T]) hybrid_property[_T]

Provide a modifying decorator that defines an UPDATE tuple producing method.

The method accepts a single value, which is the value to be rendered into the SET clause of an UPDATE statement. The method should then process this value into individual column expressions that fit into the ultimate SET clause, and return them as a sequence of 2-tuples. Each tuple contains a column expression as the key and a value to be rendered.

E.g.:

class Person(Base):
    # ...

    first_name = Column(String)
    last_name = Column(String)

    @hybrid_property
    def fullname(self):
        return first_name + " " + last_name

    @fullname.update_expression
    def fullname(cls, value):
        fname, lname = value.split(" ", 1)
        return [(cls.first_name, fname), (cls.last_name, lname)]

Added in version 1.2.

server_modules.is_signin(request: Request) bool

request에 jwt가 있는지 확인합니다.

매개변수:

request (Request) – FastAPI의 request 객체

server_modules.mapped_column(__name_pos: str | _TypeEngineArgument[Any] | SchemaEventTarget | None = None, __type_pos: _TypeEngineArgument[Any] | SchemaEventTarget | None = None, *args: SchemaEventTarget, init: _NoArg | bool = _NoArg.NO_ARG, repr: _NoArg | bool = _NoArg.NO_ARG, default: Any | None = _NoArg.NO_ARG, default_factory: _NoArg | Callable[[], _T] = _NoArg.NO_ARG, compare: _NoArg | bool = _NoArg.NO_ARG, kw_only: _NoArg | bool = _NoArg.NO_ARG, hash: _NoArg | bool | None = _NoArg.NO_ARG, nullable: bool | Literal[SchemaConst.NULL_UNSPECIFIED] | None = SchemaConst.NULL_UNSPECIFIED, primary_key: bool | None = False, deferred: _NoArg | bool = _NoArg.NO_ARG, deferred_group: str | None = None, deferred_raiseload: bool | None = None, use_existing_column: bool = False, name: str | None = None, type_: _TypeEngineArgument[Any] | None = None, autoincrement: _AutoIncrementType = 'auto', doc: str | None = None, key: str | None = None, index: bool | None = None, unique: bool | None = None, info: _InfoType | None = None, onupdate: Any | None = None, insert_default: Any | None = _NoArg.NO_ARG, server_default: _ServerDefaultArgument | None = None, server_onupdate: _ServerOnUpdateArgument | None = None, active_history: bool = False, quote: bool | None = None, system: bool = False, comment: str | None = None, sort_order: _NoArg | int = _NoArg.NO_ARG, **kw: Any) MappedColumn[Any]

declare a new ORM-mapped _schema.Column construct for use within Declarative Table configuration.

The _orm.mapped_column() function provides an ORM-aware and Python-typing-compatible construct which is used with declarative mappings to indicate an attribute that’s mapped to a Core _schema.Column object. It provides the equivalent feature as mapping an attribute to a _schema.Column object directly when using Declarative, specifically when using Declarative Table configuration.

Added in version 2.0.

_orm.mapped_column() is normally used with explicit typing along with the _orm.Mapped annotation type, where it can derive the SQL type and nullability for the column based on what’s present within the _orm.Mapped annotation. It also may be used without annotations as a drop-in replacement for how _schema.Column is used in Declarative mappings in SQLAlchemy 1.x style.

For usage examples of _orm.mapped_column(), see the documentation at orm_declarative_table.

더 보기

orm_declarative_table - complete documentation

whatsnew_20_orm_declarative_typing - migration notes for Declarative mappings using 1.x style mappings

매개변수:
  • __name – String name to give to the _schema.Column. This is an optional, positional only argument that if present must be the first positional argument passed. If omitted, the attribute name to which the _orm.mapped_column() is mapped will be used as the SQL column name.

  • __type_types.TypeEngine type or instance which will indicate the datatype to be associated with the _schema.Column. This is an optional, positional-only argument that if present must immediately follow the __name parameter if present also, or otherwise be the first positional parameter. If omitted, the ultimate type for the column may be derived either from the annotated type, or if a _schema.ForeignKey is present, from the datatype of the referenced column.

  • *args – Additional positional arguments include constructs such as _schema.ForeignKey, _schema.CheckConstraint, and _schema.Identity, which are passed through to the constructed _schema.Column.

  • nullable – Optional bool, whether the column should be “NULL” or “NOT NULL”. If omitted, the nullability is derived from the type annotation based on whether or not typing.Optional is present. nullable defaults to True otherwise for non-primary key columns, and False for primary key columns.

  • primary_key – optional bool, indicates the _schema.Column would be part of the table’s primary key or not.

  • deferred

    Optional bool - this keyword argument is consumed by the ORM declarative process, and is not part of the _schema.Column itself; instead, it indicates that this column should be “deferred” for loading as though mapped by _orm.deferred().

    더 보기

    orm_queryguide_deferred_declarative

  • deferred_group

    Implies :paramref:`_orm.mapped_column.deferred` to True, and set the :paramref:`_orm.deferred.group` parameter.

    더 보기

    orm_queryguide_deferred_group

  • deferred_raiseload

    Implies :paramref:`_orm.mapped_column.deferred` to True, and set the :paramref:`_orm.deferred.raiseload` parameter.

    더 보기

    orm_queryguide_deferred_raiseload

  • use_existing_column

    if True, will attempt to locate the given column name on an inherited superclass (typically single inheriting superclass), and if present, will not produce a new column, mapping to the superclass column as though it were omitted from this class. This is used for mixins that add new columns to an inherited superclass.

    더 보기

    orm_inheritance_column_conflicts

    Added in version 2.0.0b4.

  • default

    Passed directly to the :paramref:`_schema.Column.default` parameter if the :paramref:`_orm.mapped_column.insert_default` parameter is not present. Additionally, when used with orm_declarative_native_dataclasses, indicates a default Python value that should be applied to the keyword constructor within the generated __init__() method.

    Note that in the case of dataclass generation when :paramref:`_orm.mapped_column.insert_default` is not present, this means the :paramref:`_orm.mapped_column.default` value is used in two places, both the __init__() method as well as the :paramref:`_schema.Column.default` parameter. While this behavior may change in a future release, for the moment this tends to “work out”; a default of None will mean that the _schema.Column gets no default generator, whereas a default that refers to a non-None Python or SQL expression value will be assigned up front on the object when __init__() is called, which is the same value that the Core _sql.Insert construct would use in any case, leading to the same end result.

    참고

    When using Core level column defaults that are callables to be interpreted by the underlying _schema.Column in conjunction with ORM-mapped dataclasses, especially those that are context-aware default functions, the :paramref:`_orm.mapped_column.insert_default` parameter must be used instead. This is necessary to disambiguate the callable from being interpreted as a dataclass level default.

  • insert_default

    Passed directly to the :paramref:`_schema.Column.default` parameter; will supersede the value of :paramref:`_orm.mapped_column.default` when present, however :paramref:`_orm.mapped_column.default` will always apply to the constructor default for a dataclasses mapping.

  • sort_order

    An integer that indicates how this mapped column should be sorted compared to the others when the ORM is creating a _schema.Table. Among mapped columns that have the same value the default ordering is used, placing first the mapped columns defined in the main class, then the ones in the super classes. Defaults to 0. The sort is ascending.

    Added in version 2.0.4.

  • active_history=False

    When True, indicates that the “previous” value for a scalar attribute should be loaded when replaced, if not already loaded. Normally, history tracking logic for simple non-primary-key scalar values only needs to be aware of the “new” value in order to perform a flush. This flag is available for applications that make use of attributes.get_history() or Session.is_modified() which also need to know the “previous” value of the attribute.

    Added in version 2.0.10.

  • init – Specific to orm_declarative_native_dataclasses, specifies if the mapped attribute should be part of the __init__() method as generated by the dataclass process.

  • repr – Specific to orm_declarative_native_dataclasses, specifies if the mapped attribute should be part of the __repr__() method as generated by the dataclass process.

  • default_factory

    Specific to orm_declarative_native_dataclasses, specifies a default-value generation function that will take place as part of the __init__() method as generated by the dataclass process.

  • compare

    Specific to orm_declarative_native_dataclasses, indicates if this field should be included in comparison operations when generating the __eq__() and __ne__() methods for the mapped class.

    Added in version 2.0.0b4.

  • kw_only – Specific to orm_declarative_native_dataclasses, indicates if this field should be marked as keyword-only when generating the __init__().

  • hash

    Specific to orm_declarative_native_dataclasses, controls if this field is included when generating the __hash__() method for the mapped class.

    Added in version 2.0.36.

  • **kw – All remaining keyword arguments are passed through to the constructor for the _schema.Column.

async server_modules.model_to_excel(db_model: type[M], items: Sequence, scope: str | None = None, pick: str | None = None) BytesIO

모델을 엑셀로 변환합니다.

class server_modules.omit(omit_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'])
class server_modules.omit(omit_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], _: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'])
class server_modules.omit(omit_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], _: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], __: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'])
class server_modules.omit(omit_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], _: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], __: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], ___: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'])

기반 클래스: DevfiveColumnType

column 을 omit 합니다.

__init__(omit_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete']) None
__init__(omit_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], _: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete']) None
__init__(omit_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], _: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], __: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete']) None
__init__(omit_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], _: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], __: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], ___: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete']) None

__init__.

classmethod __class_getitem__(omit_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete']) Self
classmethod __class_getitem__(omit_type: tuple[Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], ...]) Self

See PEP 585.

class server_modules.pick(pick_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'])
class server_modules.pick(pick_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], _: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'])
class server_modules.pick(pick_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], _: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], __: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'])
class server_modules.pick(pick_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], _: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], __: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], ___: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'])

기반 클래스: DevfiveColumnType

column 을 pick 합니다.

__init__(pick_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete']) None
__init__(pick_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], _: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete']) None
__init__(pick_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], _: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], __: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete']) None
__init__(pick_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], _: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], __: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], ___: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete']) None

__init__.

classmethod __class_getitem__(pick_type: Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete']) Self
classmethod __class_getitem__(pick_type: tuple[Literal['get', 'list', 'one', 'create', 'update', 'patch', 'delete'], ...]) Self

See PEP 585.

class server_modules.pk(include: bool)

기반 클래스: DevfiveColumnType

column 에 pk 를 추가합니다.

__init__(include: bool) None

__init__.

Args:

include (bool): create update 등 pk 를 설정할 수 있게 합니다.

classmethod __class_getitem__(include: bool) Self

See PEP 585.

class server_modules.rel(rel_: AnyStr, *, uselist: bool | None = None, secondary: AnyStr | None = None, cascade: str | None = None, back_populates: str | None = None, foreign_keys: str | None = None, lazy: str | None = None, **kwargs: Any)

기반 클래스: DevfiveColumnType

해당 필드를 relation 으로 설정합니다.

__init__(rel_: AnyStr, *, uselist: bool | None = None, secondary: AnyStr | None = None, cascade: str | None = None, back_populates: str | None = None, foreign_keys: str | None = None, lazy: str | None = None, **kwargs: Any) None

__init__.

create_relationship(model: type[Model] | None = None, key: str = '') Relationship

Relationship 을 생성합니다.

key 가 _ 로 시작한다면 select 로 설정하고 그것이 아니면 selectin 으로 설정하여 무조건 로딩되는 경우 속도를 증가시킵니다.

classmethod __class_getitem__(rel_: AnyStr | type[str], *, uselist: bool | None = None, secondary: AnyStr | None = None, cascade: str | None = None, back_populates: str | None = None) Self

See PEP 585.

server_modules.relationship(argument: _RelationshipArgumentType[Any] | None = None, secondary: _RelationshipSecondaryArgument | None = None, *, uselist: bool | None = None, collection_class: Type[Collection[Any]] | Callable[[], Collection[Any]] | None = None, primaryjoin: _RelationshipJoinConditionArgument | None = None, secondaryjoin: _RelationshipJoinConditionArgument | None = None, back_populates: str | None = None, order_by: _ORMOrderByArgument = False, backref: ORMBackrefArgument | None = None, overlaps: str | None = None, post_update: bool = False, cascade: str = 'save-update, merge', viewonly: bool = False, init: _NoArg | bool = _NoArg.NO_ARG, repr: _NoArg | bool = _NoArg.NO_ARG, default: _NoArg | _T = _NoArg.NO_ARG, default_factory: _NoArg | Callable[[], _T] = _NoArg.NO_ARG, compare: _NoArg | bool = _NoArg.NO_ARG, kw_only: _NoArg | bool = _NoArg.NO_ARG, hash: _NoArg | bool | None = _NoArg.NO_ARG, lazy: _LazyLoadArgumentType = 'select', passive_deletes: Literal['all'] | bool = False, passive_updates: bool = True, active_history: bool = False, enable_typechecks: bool = True, foreign_keys: _ORMColCollectionArgument | None = None, remote_side: _ORMColCollectionArgument | None = None, join_depth: int | None = None, comparator_factory: Type[RelationshipProperty.Comparator[Any]] | None = None, single_parent: bool = False, innerjoin: bool = False, distinct_target_key: bool | None = None, load_on_pending: bool = False, query_class: Type[Query[Any]] | None = None, info: _InfoType | None = None, omit_join: Literal[None, False] = None, sync_backref: bool | None = None, **kw: Any) _RelationshipDeclared[Any]

Provide a relationship between two mapped classes.

This corresponds to a parent-child or associative table relationship. The constructed class is an instance of Relationship.

더 보기

tutorial_orm_related_objects - tutorial introduction to _orm.relationship() in the unified_tutorial

relationship_config_toplevel - narrative documentation

매개변수:
  • argument

    This parameter refers to the class that is to be related. It accepts several forms, including a direct reference to the target class itself, the _orm.Mapper instance for the target class, a Python callable / lambda that will return a reference to the class or _orm.Mapper when called, and finally a string name for the class, which will be resolved from the _orm.registry in use in order to locate the class, e.g.:

    class SomeClass(Base):
        # ...
    
        related = relationship("RelatedClass")
    

    The :paramref:`_orm.relationship.argument` may also be omitted from the _orm.relationship() construct entirely, and instead placed inside a _orm.Mapped annotation on the left side, which should include a Python collection type if the relationship is expected to be a collection, such as:

    class SomeClass(Base):
        # ...
    
        related_items: Mapped[List["RelatedItem"]] = relationship()
    

    Or for a many-to-one or one-to-one relationship:

    class SomeClass(Base):
        # ...
    
        related_item: Mapped["RelatedItem"] = relationship()
    

    더 보기

    orm_declarative_properties - further detail on relationship configuration when using Declarative.

  • secondary

    For a many-to-many relationship, specifies the intermediary table, and is typically an instance of _schema.Table. In less common circumstances, the argument may also be specified as an _expression.Alias construct, or even a _expression.Join construct.

    :paramref:`_orm.relationship.secondary` may also be passed as a callable function which is evaluated at mapper initialization time. When using Declarative, it may also be a string argument noting the name of a _schema.Table that is present in the _schema.MetaData collection associated with the parent-mapped _schema.Table.

    경고

    When passed as a Python-evaluable string, the argument is interpreted using Python’s eval() function. DO NOT PASS UNTRUSTED INPUT TO THIS STRING. See declarative_relationship_eval for details on declarative evaluation of _orm.relationship() arguments.

    The :paramref:`_orm.relationship.secondary` keyword argument is typically applied in the case where the intermediary _schema.Table is not otherwise expressed in any direct class mapping. If the “secondary” table is also explicitly mapped elsewhere (e.g. as in association_pattern), one should consider applying the :paramref:`_orm.relationship.viewonly` flag so that this _orm.relationship() is not used for persistence operations which may conflict with those of the association object pattern.

    더 보기

    relationships_many_to_many - Reference example of “many to many”.

    self_referential_many_to_many - Specifics on using many-to-many in a self-referential case.

    declarative_many_to_many - Additional options when using Declarative.

    association_pattern - an alternative to :paramref:`_orm.relationship.secondary` when composing association table relationships, allowing additional attributes to be specified on the association table.

    composite_secondary_join - a lesser-used pattern which in some cases can enable complex _orm.relationship() SQL conditions to be used.

  • active_history=False – When True, indicates that the “previous” value for a many-to-one reference should be loaded when replaced, if not already loaded. Normally, history tracking logic for simple many-to-ones only needs to be aware of the “new” value in order to perform a flush. This flag is available for applications that make use of attributes.get_history() which also need to know the “previous” value of the attribute.

  • backref

    A reference to a string relationship name, or a _orm.backref() construct, which will be used to automatically generate a new _orm.relationship() on the related class, which then refers to this one using a bi-directional :paramref:`_orm.relationship.back_populates` configuration.

    In modern Python, explicit use of _orm.relationship() with :paramref:`_orm.relationship.back_populates` should be preferred, as it is more robust in terms of mapper configuration as well as more conceptually straightforward. It also integrates with new PEP 484 typing features introduced in SQLAlchemy 2.0 which is not possible with dynamically generated attributes.

    더 보기

    relationships_backref - notes on using :paramref:`_orm.relationship.backref`

    tutorial_orm_related_objects - in the unified_tutorial, presents an overview of bi-directional relationship configuration and behaviors using :paramref:`_orm.relationship.back_populates`

    backref() - allows control over _orm.relationship() configuration when using :paramref:`_orm.relationship.backref`.

  • back_populates

    Indicates the name of a _orm.relationship() on the related class that will be synchronized with this one. It is usually expected that the _orm.relationship() on the related class also refer to this one. This allows objects on both sides of each _orm.relationship() to synchronize in-Python state changes and also provides directives to the unit of work flush process how changes along these relationships should be persisted.

    더 보기

    tutorial_orm_related_objects - in the unified_tutorial, presents an overview of bi-directional relationship configuration and behaviors.

    relationship_patterns - includes many examples of :paramref:`_orm.relationship.back_populates`.

    :paramref:`_orm.relationship.backref` - legacy form which allows more succinct configuration, but does not support explicit typing

  • overlaps

    A string name or comma-delimited set of names of other relationships on either this mapper, a descendant mapper, or a target mapper with which this relationship may write to the same foreign keys upon persistence. The only effect this has is to eliminate the warning that this relationship will conflict with another upon persistence. This is used for such relationships that are truly capable of conflicting with each other on write, but the application will ensure that no such conflicts occur.

    Added in version 1.4.

    더 보기

    error_qzyx - usage example

  • cascade

    A comma-separated list of cascade rules which determines how Session operations should be “cascaded” from parent to child. This defaults to False, which means the default cascade should be used - this default cascade is "save-update, merge".

    The available cascades are save-update, merge, expunge, delete, delete-orphan, and refresh-expire. An additional option, all indicates shorthand for "save-update, merge, refresh-expire, expunge, delete", and is often used as in "all, delete-orphan" to indicate that related objects should follow along with the parent object in all cases, and be deleted when de-associated.

    더 보기

    unitofwork_cascades - Full detail on each of the available cascade options.

  • cascade_backrefs=False

    Legacy; this flag is always False.

    버전 2.0에서 변경: “cascade_backrefs” functionality has been removed.

  • collection_class

    A class or callable that returns a new list-holding object. will be used in place of a plain list for storing elements.

    더 보기

    custom_collections - Introductory documentation and examples.

  • comparator_factory

    A class which extends Relationship.Comparator which provides custom SQL clause generation for comparison operations.

    더 보기

    PropComparator - some detail on redefining comparators at this level.

    custom_comparators - Brief intro to this feature.

  • distinct_target_key=None

    Indicate if a “subquery” eager load should apply the DISTINCT keyword to the innermost SELECT statement. When left as None, the DISTINCT keyword will be applied in those cases when the target columns do not comprise the full primary key of the target table. When set to True, the DISTINCT keyword is applied to the innermost SELECT unconditionally.

    It may be desirable to set this flag to False when the DISTINCT is reducing performance of the innermost subquery beyond that of what duplicate innermost rows may be causing.

    더 보기

    loading_toplevel - includes an introduction to subquery eager loading.

  • doc – Docstring which will be applied to the resulting descriptor.

  • foreign_keys

    A list of columns which are to be used as “foreign key” columns, or columns which refer to the value in a remote column, within the context of this _orm.relationship() object’s :paramref:`_orm.relationship.primaryjoin` condition. That is, if the :paramref:`_orm.relationship.primaryjoin` condition of this _orm.relationship() is a.id == b.a_id, and the values in b.a_id are required to be present in a.id, then the “foreign key” column of this _orm.relationship() is b.a_id.

    In normal cases, the :paramref:`_orm.relationship.foreign_keys` parameter is not required. _orm.relationship() will automatically determine which columns in the :paramref:`_orm.relationship.primaryjoin` condition are to be considered “foreign key” columns based on those _schema.Column objects that specify _schema.ForeignKey, or are otherwise listed as referencing columns in a _schema.ForeignKeyConstraint construct. :paramref:`_orm.relationship.foreign_keys` is only needed when:

    1. There is more than one way to construct a join from the local table to the remote table, as there are multiple foreign key references present. Setting foreign_keys will limit the _orm.relationship() to consider just those columns specified here as “foreign”.

    2. The _schema.Table being mapped does not actually have _schema.ForeignKey or _schema.ForeignKeyConstraint constructs present, often because the table was reflected from a database that does not support foreign key reflection (MySQL MyISAM).

    3. The :paramref:`_orm.relationship.primaryjoin` argument is used to construct a non-standard join condition, which makes use of columns or expressions that do not normally refer to their “parent” column, such as a join condition expressed by a complex comparison using a SQL function.

    The _orm.relationship() construct will raise informative error messages that suggest the use of the :paramref:`_orm.relationship.foreign_keys` parameter when presented with an ambiguous condition. In typical cases, if _orm.relationship() doesn’t raise any exceptions, the :paramref:`_orm.relationship.foreign_keys` parameter is usually not needed.

    :paramref:`_orm.relationship.foreign_keys` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

    경고

    When passed as a Python-evaluable string, the argument is interpreted using Python’s eval() function. DO NOT PASS UNTRUSTED INPUT TO THIS STRING. See declarative_relationship_eval for details on declarative evaluation of _orm.relationship() arguments.

    더 보기

    relationship_foreign_keys

    relationship_custom_foreign

    foreign() - allows direct annotation of the “foreign” columns within a :paramref:`_orm.relationship.primaryjoin` condition.

  • info – Optional data dictionary which will be populated into the MapperProperty.info attribute of this object.

  • innerjoin=False

    When True, joined eager loads will use an inner join to join against related tables instead of an outer join. The purpose of this option is generally one of performance, as inner joins generally perform better than outer joins.

    This flag can be set to True when the relationship references an object via many-to-one using local foreign keys that are not nullable, or when the reference is one-to-one or a collection that is guaranteed to have one or at least one entry.

    The option supports the same “nested” and “unnested” options as that of :paramref:`_orm.joinedload.innerjoin`. See that flag for details on nested / unnested behaviors.

    더 보기

    :paramref:`_orm.joinedload.innerjoin` - the option as specified by loader option, including detail on nesting behavior.

    what_kind_of_loading - Discussion of some details of various loader options.

  • join_depth

    When non-None, an integer value indicating how many levels deep “eager” loaders should join on a self-referring or cyclical relationship. The number counts how many times the same Mapper shall be present in the loading condition along a particular join branch. When left at its default of None, eager loaders will stop chaining when they encounter a the same target mapper which is already higher up in the chain. This option applies both to joined- and subquery- eager loaders.

    더 보기

    self_referential_eager_loading - Introductory documentation and examples.

  • lazy='select'

    specifies How the related items should be loaded. Default value is select. Values include:

    • select - items should be loaded lazily when the property is first accessed, using a separate SELECT statement, or identity map fetch for simple many-to-one references.

    • immediate - items should be loaded as the parents are loaded, using a separate SELECT statement, or identity map fetch for simple many-to-one references.

    • joined - items should be loaded “eagerly” in the same query as that of the parent, using a JOIN or LEFT OUTER JOIN. Whether the join is “outer” or not is determined by the :paramref:`_orm.relationship.innerjoin` parameter.

    • subquery - items should be loaded “eagerly” as the parents are loaded, using one additional SQL statement, which issues a JOIN to a subquery of the original statement, for each collection requested.

    • selectin - items should be loaded “eagerly” as the parents are loaded, using one or more additional SQL statements, which issues a JOIN to the immediate parent object, specifying primary key identifiers using an IN clause.

    • noload - no loading should occur at any time. The related collection will remain empty. The noload strategy is not recommended for general use. For a general use “never load” approach, see write_only_relationship

    • raise - lazy loading is disallowed; accessing the attribute, if its value were not already loaded via eager loading, will raise an InvalidRequestError. This strategy can be used when objects are to be detached from their attached Session after they are loaded.

    • raise_on_sql - lazy loading that emits SQL is disallowed; accessing the attribute, if its value were not already loaded via eager loading, will raise an InvalidRequestError, if the lazy load needs to emit SQL. If the lazy load can pull the related value from the identity map or determine that it should be None, the value is loaded. This strategy can be used when objects will remain associated with the attached Session, however additional SELECT statements should be blocked.

    • write_only - the attribute will be configured with a special “virtual collection” that may receive _orm.WriteOnlyCollection.add() and _orm.WriteOnlyCollection.remove() commands to add or remove individual objects, but will not under any circumstances load or iterate the full set of objects from the database directly. Instead, methods such as _orm.WriteOnlyCollection.select(), _orm.WriteOnlyCollection.insert(), _orm.WriteOnlyCollection.update() and _orm.WriteOnlyCollection.delete() are provided which generate SQL constructs that may be used to load and modify rows in bulk. Used for large collections that are never appropriate to load at once into memory.

      The write_only loader style is configured automatically when the _orm.WriteOnlyMapped annotation is provided on the left hand side within a Declarative mapping. See the section write_only_relationship for examples.

      Added in version 2.0.

      더 보기

      write_only_relationship - in the queryguide_toplevel

    • dynamic - the attribute will return a pre-configured _query.Query object for all read operations, onto which further filtering operations can be applied before iterating the results.

      The dynamic loader style is configured automatically when the _orm.DynamicMapped annotation is provided on the left hand side within a Declarative mapping. See the section dynamic_relationship for examples.

      더 보기

      dynamic_relationship - in the queryguide_toplevel

      write_only_relationship - more generally useful approach for large collections that should not fully load into memory

    • True - a synonym for ‘select’

    • False - a synonym for ‘joined’

    • None - a synonym for ‘noload’

    더 보기

    orm_queryguide_relationship_loaders - Full documentation on relationship loader configuration in the queryguide_toplevel.

  • load_on_pending=False

    Indicates loading behavior for transient or pending parent objects.

    When set to True, causes the lazy-loader to issue a query for a parent object that is not persistent, meaning it has never been flushed. This may take effect for a pending object when autoflush is disabled, or for a transient object that has been “attached” to a Session but is not part of its pending collection.

    The :paramref:`_orm.relationship.load_on_pending` flag does not improve behavior when the ORM is used normally - object references should be constructed at the object level, not at the foreign key level, so that they are present in an ordinary way before a flush proceeds. This flag is not not intended for general use.

    더 보기

    Session.enable_relationship_loading() - this method establishes “load on pending” behavior for the whole object, and also allows loading on objects that remain transient or detached.

  • order_by

    Indicates the ordering that should be applied when loading these items. :paramref:`_orm.relationship.order_by` is expected to refer to one of the _schema.Column objects to which the target class is mapped, or the attribute itself bound to the target class which refers to the column.

    :paramref:`_orm.relationship.order_by` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

    경고

    When passed as a Python-evaluable string, the argument is interpreted using Python’s eval() function. DO NOT PASS UNTRUSTED INPUT TO THIS STRING. See declarative_relationship_eval for details on declarative evaluation of _orm.relationship() arguments.

  • passive_deletes=False

    Indicates loading behavior during delete operations.

    A value of True indicates that unloaded child items should not be loaded during a delete operation on the parent. Normally, when a parent item is deleted, all child items are loaded so that they can either be marked as deleted, or have their foreign key to the parent set to NULL. Marking this flag as True usually implies an ON DELETE <CASCADE|SET NULL> rule is in place which will handle updating/deleting child rows on the database side.

    Additionally, setting the flag to the string value ‘all’ will disable the “nulling out” of the child foreign keys, when the parent object is deleted and there is no delete or delete-orphan cascade enabled. This is typically used when a triggering or error raise scenario is in place on the database side. Note that the foreign key attributes on in-session child objects will not be changed after a flush occurs so this is a very special use-case setting. Additionally, the “nulling out” will still occur if the child object is de-associated with the parent.

    더 보기

    passive_deletes - Introductory documentation and examples.

  • passive_updates=True

    Indicates the persistence behavior to take when a referenced primary key value changes in place, indicating that the referencing foreign key columns will also need their value changed.

    When True, it is assumed that ON UPDATE CASCADE is configured on the foreign key in the database, and that the database will handle propagation of an UPDATE from a source column to dependent rows. When False, the SQLAlchemy _orm.relationship() construct will attempt to emit its own UPDATE statements to modify related targets. However note that SQLAlchemy cannot emit an UPDATE for more than one level of cascade. Also, setting this flag to False is not compatible in the case where the database is in fact enforcing referential integrity, unless those constraints are explicitly “deferred”, if the target backend supports it.

    It is highly advised that an application which is employing mutable primary keys keeps passive_updates set to True, and instead uses the referential integrity features of the database itself in order to handle the change efficiently and fully.

    더 보기

    passive_updates - Introductory documentation and examples.

    :paramref:`.mapper.passive_updates` - a similar flag which takes effect for joined-table inheritance mappings.

  • post_update

    This indicates that the relationship should be handled by a second UPDATE statement after an INSERT or before a DELETE. This flag is used to handle saving bi-directional dependencies between two individual rows (i.e. each row references the other), where it would otherwise be impossible to INSERT or DELETE both rows fully since one row exists before the other. Use this flag when a particular mapping arrangement will incur two rows that are dependent on each other, such as a table that has a one-to-many relationship to a set of child rows, and also has a column that references a single child row within that list (i.e. both tables contain a foreign key to each other). If a flush operation returns an error that a “cyclical dependency” was detected, this is a cue that you might want to use :paramref:`_orm.relationship.post_update` to “break” the cycle.

    더 보기

    post_update - Introductory documentation and examples.

  • primaryjoin

    A SQL expression that will be used as the primary join of the child object against the parent object, or in a many-to-many relationship the join of the parent object to the association table. By default, this value is computed based on the foreign key relationships of the parent and child tables (or association table).

    :paramref:`_orm.relationship.primaryjoin` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

    경고

    When passed as a Python-evaluable string, the argument is interpreted using Python’s eval() function. DO NOT PASS UNTRUSTED INPUT TO THIS STRING. See declarative_relationship_eval for details on declarative evaluation of _orm.relationship() arguments.

    더 보기

    relationship_primaryjoin

  • remote_side

    Used for self-referential relationships, indicates the column or list of columns that form the “remote side” of the relationship.

    :paramref:`_orm.relationship.remote_side` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

    경고

    When passed as a Python-evaluable string, the argument is interpreted using Python’s eval() function. DO NOT PASS UNTRUSTED INPUT TO THIS STRING. See declarative_relationship_eval for details on declarative evaluation of _orm.relationship() arguments.

    더 보기

    self_referential - in-depth explanation of how :paramref:`_orm.relationship.remote_side` is used to configure self-referential relationships.

    remote() - an annotation function that accomplishes the same purpose as :paramref:`_orm.relationship.remote_side`, typically when a custom :paramref:`_orm.relationship.primaryjoin` condition is used.

  • query_class

    A _query.Query subclass that will be used internally by the AppenderQuery returned by a “dynamic” relationship, that is, a relationship that specifies lazy="dynamic" or was otherwise constructed using the _orm.dynamic_loader() function.

    더 보기

    dynamic_relationship - Introduction to “dynamic” relationship loaders.

  • secondaryjoin

    A SQL expression that will be used as the join of an association table to the child object. By default, this value is computed based on the foreign key relationships of the association and child tables.

    :paramref:`_orm.relationship.secondaryjoin` may also be passed as a callable function which is evaluated at mapper initialization time, and may be passed as a Python-evaluable string when using Declarative.

    경고

    When passed as a Python-evaluable string, the argument is interpreted using Python’s eval() function. DO NOT PASS UNTRUSTED INPUT TO THIS STRING. See declarative_relationship_eval for details on declarative evaluation of _orm.relationship() arguments.

    더 보기

    relationship_primaryjoin

  • single_parent

    When True, installs a validator which will prevent objects from being associated with more than one parent at a time. This is used for many-to-one or many-to-many relationships that should be treated either as one-to-one or one-to-many. Its usage is optional, except for _orm.relationship() constructs which are many-to-one or many-to-many and also specify the delete-orphan cascade option. The _orm.relationship() construct itself will raise an error instructing when this option is required.

    더 보기

    unitofwork_cascades - includes detail on when the :paramref:`_orm.relationship.single_parent` flag may be appropriate.

  • uselist

    A boolean that indicates if this property should be loaded as a list or a scalar. In most cases, this value is determined automatically by _orm.relationship() at mapper configuration time. When using explicit _orm.Mapped annotations, :paramref:`_orm.relationship.uselist` may be derived from the whether or not the annotation within _orm.Mapped contains a collection class. Otherwise, :paramref:`_orm.relationship.uselist` may be derived from the type and direction of the relationship - one to many forms a list, many to one forms a scalar, many to many is a list. If a scalar is desired where normally a list would be present, such as a bi-directional one-to-one relationship, use an appropriate _orm.Mapped annotation or set :paramref:`_orm.relationship.uselist` to False.

    The :paramref:`_orm.relationship.uselist` flag is also available on an existing _orm.relationship() construct as a read-only attribute, which can be used to determine if this _orm.relationship() deals with collections or scalar attributes:

    >>> User.addresses.property.uselist
    True
    

    더 보기

    relationships_one_to_one - Introduction to the “one to one” relationship pattern, which is typically when an alternate setting for :paramref:`_orm.relationship.uselist` is involved.

  • viewonly=False

    When set to True, the relationship is used only for loading objects, and not for any persistence operation. A _orm.relationship() which specifies :paramref:`_orm.relationship.viewonly` can work with a wider range of SQL operations within the :paramref:`_orm.relationship.primaryjoin` condition, including operations that feature the use of a variety of comparison operators as well as SQL functions such as _expression.cast(). The :paramref:`_orm.relationship.viewonly` flag is also of general use when defining any kind of _orm.relationship() that doesn’t represent the full set of related objects, to prevent modifications of the collection from resulting in persistence operations.

    더 보기

    relationship_viewonly_notes - more details on best practices when using :paramref:`_orm.relationship.viewonly`.

  • sync_backref

    A boolean that enables the events used to synchronize the in-Python attributes when this relationship is target of either :paramref:`_orm.relationship.backref` or :paramref:`_orm.relationship.back_populates`.

    Defaults to None, which indicates that an automatic value should be selected based on the value of the :paramref:`_orm.relationship.viewonly` flag. When left at its default, changes in state will be back-populated only if neither sides of a relationship is viewonly.

    Added in version 1.3.17.

    버전 1.4에서 변경: - A relationship that specifies :paramref:`_orm.relationship.viewonly` automatically implies that :paramref:`_orm.relationship.sync_backref` is False.

  • omit_join

    Allows manual control over the “selectin” automatic join optimization. Set to False to disable the “omit join” feature added in SQLAlchemy 1.3; or leave as None to leave automatic optimization in place.

    참고

    This flag may only be set to False. It is not necessary to set it to True as the “omit_join” optimization is automatically detected; if it is not detected, then the optimization is not supported.

    버전 1.3.11에서 변경: setting omit_join to True will now emit a warning as this was not the intended use of this flag.

    Added in version 1.3.

  • init – Specific to orm_declarative_native_dataclasses, specifies if the mapped attribute should be part of the __init__() method as generated by the dataclass process.

  • repr – Specific to orm_declarative_native_dataclasses, specifies if the mapped attribute should be part of the __repr__() method as generated by the dataclass process.

  • default_factory – Specific to orm_declarative_native_dataclasses, specifies a default-value generation function that will take place as part of the __init__() method as generated by the dataclass process.

  • compare

    Specific to orm_declarative_native_dataclasses, indicates if this field should be included in comparison operations when generating the __eq__() and __ne__() methods for the mapped class.

    Added in version 2.0.0b4.

  • kw_only – Specific to orm_declarative_native_dataclasses, indicates if this field should be marked as keyword-only when generating the __init__().

  • hash

    Specific to orm_declarative_native_dataclasses, controls if this field is included when generating the __hash__() method for the mapped class.

    Added in version 2.0.36.

server_modules.request

:py:class:`~server_modules.middlewares.request_session.create_middleware_and_request_proxy.<locals>.RequestSession`의 별칭

server_modules.select(__ent0: _TCCA[_T0]) Select[Tuple[_T0]]
server_modules.select(__ent0: _TCCA[_T0], __ent1: _TCCA[_T1]) Select[Tuple[_T0, _T1]]
server_modules.select(__ent0: _TCCA[_T0], __ent1: _TCCA[_T1], __ent2: _TCCA[_T2]) Select[Tuple[_T0, _T1, _T2]]
server_modules.select(__ent0: _TCCA[_T0], __ent1: _TCCA[_T1], __ent2: _TCCA[_T2], __ent3: _TCCA[_T3]) Select[Tuple[_T0, _T1, _T2, _T3]]
server_modules.select(__ent0: _TCCA[_T0], __ent1: _TCCA[_T1], __ent2: _TCCA[_T2], __ent3: _TCCA[_T3], __ent4: _TCCA[_T4]) Select[Tuple[_T0, _T1, _T2, _T3, _T4]]
server_modules.select(__ent0: _TCCA[_T0], __ent1: _TCCA[_T1], __ent2: _TCCA[_T2], __ent3: _TCCA[_T3], __ent4: _TCCA[_T4], __ent5: _TCCA[_T5]) Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]]
server_modules.select(__ent0: _TCCA[_T0], __ent1: _TCCA[_T1], __ent2: _TCCA[_T2], __ent3: _TCCA[_T3], __ent4: _TCCA[_T4], __ent5: _TCCA[_T5], __ent6: _TCCA[_T6]) Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]]
server_modules.select(__ent0: _TCCA[_T0], __ent1: _TCCA[_T1], __ent2: _TCCA[_T2], __ent3: _TCCA[_T3], __ent4: _TCCA[_T4], __ent5: _TCCA[_T5], __ent6: _TCCA[_T6], __ent7: _TCCA[_T7]) Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]]
server_modules.select(__ent0: _TCCA[_T0], __ent1: _TCCA[_T1], __ent2: _TCCA[_T2], __ent3: _TCCA[_T3], __ent4: _TCCA[_T4], __ent5: _TCCA[_T5], __ent6: _TCCA[_T6], __ent7: _TCCA[_T7], __ent8: _TCCA[_T8]) Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8]]
server_modules.select(__ent0: _TCCA[_T0], __ent1: _TCCA[_T1], __ent2: _TCCA[_T2], __ent3: _TCCA[_T3], __ent4: _TCCA[_T4], __ent5: _TCCA[_T5], __ent6: _TCCA[_T6], __ent7: _TCCA[_T7], __ent8: _TCCA[_T8], __ent9: _TCCA[_T9]) Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8, _T9]]
server_modules.select(*entities: _ColumnsClauseArgument[Any], **__kw: Any) Select

Construct a new _expression.Select.

Added in version 1.4: - The _sql.select() function now accepts column arguments positionally. The top-level _sql.select() function will automatically use the 1.x or 2.x style API based on the incoming arguments; using _sql.select() from the sqlalchemy.future module will enforce that only the 2.x style constructor is used.

Similar functionality is also available via the _expression.FromClause.select() method on any _expression.FromClause.

더 보기

tutorial_selecting_data - in the unified_tutorial

매개변수:

*entities

Entities to SELECT from. For Core usage, this is typically a series of _expression.ColumnElement and / or _expression.FromClause objects which will form the columns clause of the resulting statement. For those objects that are instances of _expression.FromClause (typically _schema.Table or _expression.Alias objects), the _expression.FromClause.c collection is extracted to form a collection of _expression.ColumnElement objects.

This parameter will also accept _expression.TextClause constructs as given, as well as ORM-mapped classes.

server_modules.send_firebase_notification(app: App, title: str, body: str, fcm_token: str, image: str | None = None, **kwargs: Any) None

Send FCM push message.

server_modules.send_firebase_notification_to_topic(app: App, title: str, body: str, topic: str, image: str | None = None, **kwargs: Any) None

Send FCM push message.

async server_modules.send_ses_email(template_file: str, receiver: str | Iterable[str], title: str, *, template_obj: dict | None = None, sender: str | None = None) None

Send email.

class server_modules.server_default(server_default_: AnyStr | bool | int)

기반 클래스: DevfiveColumnType

column 에 server_default 를 추가합니다.

__init__(server_default_: AnyStr | bool | int) None

__init__.

classmethod __class_getitem__(server_default_: AnyStr | bool | int | type[str]) Self

See PEP 585.

server_modules.subscribe_firebase_notification_topic(app: App, fcm_token: str, topic: str) None

Subscribe Topic.

class server_modules.time

기반 클래스: object

time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) –> a time object

All arguments are optional. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints.

dst()

Return self.tzinfo.dst(self).

classmethod fromisoformat()

string -> time from a string in ISO 8601 format

isoformat()

Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].

The optional argument timespec specifies the number of additional terms of the time to include. Valid options are ‘auto’, ‘hours’, ‘minutes’, ‘seconds’, ‘milliseconds’ and ‘microseconds’.

replace()

Return time with new specified fields.

strftime()

format -> strftime() style string.

tzname()

Return self.tzinfo.tzname(self).

utcoffset()

Return self.tzinfo.utcoffset(self).

class server_modules.unique(unique: AnyStr)

기반 클래스: DevfiveColumnType

column 에 unique 를 추가합니다.

unique 인스턴스일 경우 같은 key 를 가진 unique 인스턴스는 같은 것으로 유니크 규칙을 생성합니다.

__init__(unique: AnyStr) None

__init__.

classmethod __class_getitem__(unique: AnyStr | type[str]) Self

See PEP 585.

server_modules.unsubscribe_firebase_notification_topic(app: App, fcm_token: str, topic: str) None

Unsubscribe Topic.