API Reference¶
Core¶
- class flask_restlib.core.AbstractFactory¶
Базовые классы:
Generic[flask_restlib.orm.TQueryExpression,flask_restlib.orm.TQueryAdapter,flask_restlib.orm.TResourceManager,flask_restlib.core.TSchema,flask_restlib.core.TSchemaOpts,flask_restlib.core.TModel]Abstract factory.
Is used for: 1. create a persistent storage query adapter 2. creating a resource manager 3. creating an automatically generated schema
- abstract create_authorization_code_model(user_model: Type[flask_restlib.oauth2.mixins.UserMixin], client_model: Type[flask_restlib.oauth2.mixins.ClientMixin]) Type[flask_restlib.oauth2.mixins.AuthorizationCodeMixin]¶
Creates and returns the OAuth2 code class.
- abstract create_client_model(user_model: Type[flask_restlib.oauth2.mixins.UserMixin]) Type[flask_restlib.oauth2.mixins.ClientMixin]¶
Creates and returns the OAuth2 client class.
- abstract create_query_adapter(base_query: Any) flask_restlib.orm.TQueryAdapter¶
Creates and returns a queryset for retrieving resources from persistent storage.
- abstract create_query_expression(expr: Any) flask_restlib.orm.TQueryExpression¶
Creates and returns an adapter for a model attribute.
- Параметры
expr –
orm.AbstractQueryExpressionor native expression.
- abstract create_resource_manager() flask_restlib.orm.TResourceManager¶
Creates and returns a resource manager instance.
- abstract create_schema(model_class: Type[flask_restlib.core.TModel]) Type[flask_restlib.core.TSchema]¶
Creates and returns an automatic schema class.
- Параметры
model_class – A reference to the model class that describes the REST resource.
- abstract create_token_model(user_model: Type[flask_restlib.oauth2.mixins.UserMixin], client_model: Type[flask_restlib.oauth2.mixins.ClientMixin]) Type[flask_restlib.oauth2.mixins.TokenMixin]¶
Creates and returns the OAuth2 token class.
- abstract get_auto_schema_class() Type[flask_restlib.core.TSchema]¶
Returns a reference to the base class of the schema used in serialization and validation.
- abstract get_auto_schema_options_class() Type[flask_restlib.core.TSchemaOpts]¶
Returns a reference to the base auto schema options class.
- class flask_restlib.core.RestLib(app: Optional[flask.app.Flask] = None, *, factory: flask_restlib.core.TFactory, pagination_handler: Optional[flask_restlib.pagination.TPagination] = None, http_cache_instance: Optional[flask_restlib.http.THttpCache] = None, auth_options: Optional[dict] = None)¶
Базовые классы:
Generic[flask_restlib.core.TFactory,flask_restlib.pagination.TPagination,flask_restlib.http.THttpCache]- catch_exception(exc_type: Type[Exception], status_code: int = 400, callback: Optional[Callable[[flask_restlib.types.TException, flask_restlib.types.ErrorResponse], None]] = None) None¶
Catch and handle all exceptions of this type.
- Параметры
exc_type – the type of exception to catch.
status_code (int) – HTTP response code, defaults to 400.
callback – custom exception handler.
- handle_api_exception(err: flask_restlib.exceptions.RestlibError, resp: flask_restlib.types.ErrorResponse) None¶
Handle an API exception.
- handle_http_exception(err: werkzeug.exceptions.HTTPException, resp: flask_restlib.types.ErrorResponse) None¶
Handle an HTTP exception.
- register_exception_handler(exc_type: Type[Exception], status_code: int = 400) Callable[[flask_restlib.types.TFunc], flask_restlib.types.TFunc]¶
The decorator registers the function as a handler for given type of exception.
- Параметры
exc_type – the type of exception to catch.
status_code (int) – HTTP response code, defaults to 400.
Decorators¶
- flask_restlib.decorators.getattr_or_implement(getter: flask_restlib.decorators._F) flask_restlib.decorators._F¶
Used in mixins to get the value of a property in a getter method when the property is not known to exist or not.
If the property does not exist, the getter method must be implemented.
The getter method never takes any arguments.
Exceptions¶
- class flask_restlib.exceptions.RestlibError(message: Optional[str] = None, detail: Optional[dict] = None)¶
Базовые классы:
Exception
- class flask_restlib.exceptions.AuthenticationError(message: Optional[str] = None, detail: Optional[dict] = None)¶
Базовые классы:
flask_restlib.exceptions.RestlibErrorThe user did not provide credentials.
- class flask_restlib.exceptions.AuthorizationError(message: Optional[str] = None, resource: Optional[Any] = None, detail: Optional[dict] = None)¶
Базовые классы:
flask_restlib.exceptions.RestlibErrorThere are not enough rights to perform the action.
- class flask_restlib.exceptions.DuplicateResource(message: Optional[str] = None, detail: Optional[dict] = None)¶
Базовые классы:
flask_restlib.exceptions.RestlibError
- class flask_restlib.exceptions.LogicalError(message: Optional[str] = None, detail: Optional[dict] = None)¶
Базовые классы:
flask_restlib.exceptions.RestlibError
Filters¶
- class flask_restlib.filters.AbstractFilter¶
Базовые классы:
objectThe filter uses a URL query string and schema to collect and validate input data.
Filtering your results use a unique query parameter for each of your fields.
For example, to filter users based on their username: GET /users?username=admin
If you would like to add full text search to your API, use a q query parameter, for example: GET /users?q=Admin
- create_schema() Union[marshmallow.schema.Schema, Dict[str, Union[marshmallow.fields.Field, Type[marshmallow.fields.Field]]], Callable[[webargs.core.Request], marshmallow.schema.Schema]]¶
Creates and returns a schema instance that is used to validate the input data.
- filter(q: flask_restlib.types.TQueryAdapter) flask_restlib.types.TQueryAdapter¶
Applies the current filter to the given queryset and returns new queryset.
- Параметры
q – current queryset.
- abstract property schema: Union[marshmallow.schema.Schema, Dict[str, Union[marshmallow.fields.Field, Type[marshmallow.fields.Field]]], Callable[[webargs.core.Request], marshmallow.schema.Schema]]¶
Defines and returns dictionary or a Schema instance for validating input data.
Forms¶
- class flask_restlib.forms.LoginForm(*args, **kwargs)¶
Базовые классы:
flask_wtf.form.FlaskFormLogin form.
Globals¶
- flask_restlib.globals.Q(expr: Any) flask_restlib.orm.AbstractQueryExpression¶
An adapter for a model attribute.
- Параметры
column – native attribute of the model.
HTTP¶
- flask_restlib.http.url_update_query_string(url: str, params: dict[str, Any]) str¶
Given a URL, set or replace a query parameters and return the modified URL.
>>> url_update_query_string( ... 'https://example.com?offset=5&limit=25', ... { ... 'offset': 0, ... } ... ) 'https://example.com?offset=0&limit=25'
- class flask_restlib.http.AbstractHttpCache(*, methods_support_caching: Optional[set[str]] = None, methods_need_etag: Optional[set[str]] = None)¶
Базовые классы:
object
- class flask_restlib.http.HttpCache(*, methods_support_caching: Optional[set[str]] = None, methods_need_etag: Optional[set[str]] = None)¶
Базовые классы:
flask_restlib.http.AbstractHttpCache
- class flask_restlib.http.HTTPMethodOverrideMiddleware(app: WSGIApplication)¶
Базовые классы:
objecthttps://flask.palletsprojects.com/en/2.1.x/patterns/methodoverrides/
Mixins¶
OAuth2¶
Mixins¶
- class flask_restlib.oauth2.mixins.AuthorizationCodeMixin¶
Базовые классы:
authlib.oauth2.rfc6749.models.AuthorizationCodeMixin- get_client() flask_restlib.oauth2.mixins.ClientMixin¶
Returns the client to which the authorization code was issued.
- get_redirect_uri() str¶
A method to get authorization code’s
redirect_uri. For instance, the database table for authorization code has a column calledredirect_uri:def get_redirect_uri(self): return self.redirect_uri
- Результат
A URL string
- get_scope() str¶
A method to get scope of the authorization code. For instance, the column is called
scope:def get_scope(self): return self.scope
- Результат
scope string
- get_user() flask_restlib.oauth2.mixins.UserMixin¶
Returns authorization code owner.
- class flask_restlib.oauth2.mixins.ClientMixin¶
Базовые классы:
flask_restlib.oauth2.mixins.ScopeMixin,authlib.oauth2.rfc6749.models.ClientMixin- check_client_secret(client_secret: str) bool¶
Check client_secret matching with the client. For instance, in the client table, the column is called
client_secret:import secrets def check_client_secret(self, client_secret): return secrets.compare_digest(self.client_secret, client_secret)
- Параметры
client_secret – A string of client secret
- Результат
bool
- check_endpoint_auth_method(method: str, endpoint: str) bool¶
Check if client support the given method for the given endpoint. There is a
token_endpoint_auth_methoddefined via RFC7591. Developers MAY re-implement this method with:def check_endpoint_auth_method(self, method, endpoint): if endpoint == 'token': # if client table has ``token_endpoint_auth_method`` return self.token_endpoint_auth_method == method return True
Method values defined by this specification are:
- «none»: The client is a public client as defined in OAuth 2.0,
and does not have a client secret.
- «client_secret_post»: The client uses the HTTP POST parameters
as defined in OAuth 2.0
- «client_secret_basic»: The client uses HTTP Basic as defined in
OAuth 2.0
- check_grant_type(grant_type: str) bool¶
Validate if the client can handle the given grant_type. There are four grant types defined by RFC6749:
authorization_code
implicit
client_credentials
password
For instance, there is a
allowed_grant_typescolumn in your client:def check_grant_type(self, grant_type): return grant_type in self.grant_types
- Параметры
grant_type – the requested grant_type string.
- Результат
bool
- check_redirect_uri(redirect_uri: str) bool¶
Validate redirect_uri parameter in Authorization Endpoints. For instance, in the client table, there is an
allowed_redirect_uriscolumn:def check_redirect_uri(self, redirect_uri): return redirect_uri in self.allowed_redirect_uris
- Параметры
redirect_uri – A URL string for redirecting.
- Результат
bool
- check_response_type(response_type: str) bool¶
Validate if the client can handle the given response_type. There are two response types defined by RFC6749: code and token. For instance, there is a
allowed_response_typescolumn in your client:def check_response_type(self, response_type): return response_type in self.response_types
- Параметры
response_type – the requested response_type string.
- Результат
bool
- property client_info: dict[str, Any]¶
Implementation for Client Info in OAuth 2.0 Dynamic Client Registration Protocol via Section 3.2.1.
- property client_name: Optional[str]¶
Human-readable string name of the client to be presented to the end-user during authorization.
If omitted, the authorization server MAY display the raw «client_id» value to the end-user instead. It is RECOMMENDED that clients always send this field.
The value of this field MAY be internationalized, as described in Section 2.2.
- property client_uri: Optional[str]¶
URL string of a web page providing information about the client.
If present, the server SHOULD display this URL to the end-user in a clickable fashion. It is RECOMMENDED that clients always send this field. The value of this field MUST point to a valid web page. The value of this field MAY be internationalized, as described in Section 2.2.
- property contacts: list[str]¶
Array of strings representing ways to contact people responsible for this client, typically email addresses.
The authorization server MAY make these contact addresses available to end-users for support requests for the client. See Section 6 for information on Privacy Considerations.
- get_client_id() str¶
A method to return client_id of the client. For instance, the value in database is saved in a column called
client_id:def get_client_id(self): return self.client_id
- Результат
string
- get_default_redirect_uri() Optional[str]¶
A method to get client default redirect_uri. For instance, the database table for client has a column called
default_redirect_uri:def get_default_redirect_uri(self): return self.default_redirect_uri
- Результат
A URL string
- get_user() flask_restlib.oauth2.mixins.UserMixin¶
Returns client owner.
- property grant_types: list[str]¶
Array of OAuth 2.0 grant type strings that the client can use at the token endpoint.
- property jwks: list¶
Client’s JSON Web Key Set [RFC7517] document value, which contains the client’s public keys.
The value of this field MUST be a JSON object containing a valid JWK Set. These keys can be used by higher-level protocols that use signing or encryption. This parameter is intended to be used by clients that cannot use the «jwks_uri» parameter, such as native clients that cannot host public URLs. The «jwks_uri» and «jwks» parameters MUST NOT both be present in the same request or response.
- property jwks_uri: Optional[str]¶
URL string referencing the client’s JSON Web Key (JWK) Set [RFC7517] document, which contains the client’s public keys.
The value of this field MUST point to a valid JWK Set document. These keys can be used by higher-level protocols that use signing or encryption. For instance, these keys might be used by some applications for validating signed requests made to the token endpoint when using JWTs for client authentication [RFC7523]. Use of this parameter is preferred over the «jwks» parameter, as it allows for easier key rotation. The «jwks_uri» and «jwks» parameters MUST NOT both be present in the same request or response.
- property logo_uri: Optional[str]¶
URL string that references a logo for the client.
If present, the server SHOULD display this image to the end-user during approval. The value of this field MUST point to a valid image file. The value of this field MAY be internationalized, as described in Section 2.2.
- property policy_uri: Optional[str]¶
URL string that points to a human-readable privacy policy document that describes how the deployment organization collects, uses, retains, and discloses personal data.
The authorization server SHOULD display this URL to the end-user if it is provided. The value of this field MUST point to a valid web page. The value of this field MAY be internationalized, as described in Section 2.2.
- property redirect_uris: list[str]¶
Array of redirection URI strings for use in redirect-based flows such as the authorization code and implicit flows.
As required by Section 2 of OAuth 2.0 [RFC6749], clients using flows with redirection MUST register their redirection URI values.
Authorization servers that support dynamic registration for redirect-based flows MUST implement support for this metadata value.
- property response_types: list[str]¶
Array of the OAuth 2.0 response type strings that the client can use at the authorization endpoint.
- property token_endpoint_auth_method: str¶
String indicator of the requested authentication method for the token endpoint.
Values defined by this specification are:
«none»: The client is a public client as defined in OAuth 2.0, Section 2.1, and does not have a client secret.
«client_secret_post»: The client uses the HTTP POST parameters as defined in OAuth 2.0, Section 2.3.1.
«client_secret_basic»: The client uses HTTP Basic as defined in OAuth 2.0, Section 2.3.1.
Additional values can be defined via the IANA «OAuth Token Endpoint Authentication Methods» registry established in Section 4.2. Absolute URIs can also be used as values for this parameter without being registered. If unspecified or omitted, the default is «client_secret_basic», denoting the HTTP Basic authentication scheme as specified in Section 2.3.1 of OAuth 2.0.
- property tos_uri: Optional[str]¶
URL string that points to a human-readable terms of service document for the client that describes a contractual relationship between the end-user and the client that the end-user accepts when authorizing the client.
The authorization server SHOULD display this URL to the end-user if it is provided. The value of this field MUST point to a valid web page. The value of this field MAY be internationalized, as described in Section 2.2.
- class flask_restlib.oauth2.mixins.TokenMixin¶
Базовые классы:
authlib.oauth2.rfc6749.models.TokenMixin- check_client(client: flask_restlib.oauth2.mixins.ClientMixin) bool¶
A method to check if this token is issued to the given client. For instance,
client_idis saved on token table:def check_client(self, client): return self.client_id == client.client_id
- Результат
bool
- get_client() flask_restlib.oauth2.mixins.ClientMixin¶
Returns the client to which the token was issued.
- get_expires_in() int¶
A method to get the
expires_invalue of the token. e.g. the column is calledexpires_in:def get_expires_in(self): return self.expires_in
- Результат
timestamp int
- get_scope() str¶
A method to get scope of the authorization code. For instance, the column is called
scope:def get_scope(self): return self.scope
- Результат
scope string
- get_user() flask_restlib.oauth2.mixins.UserMixin¶
Returns token owner.
- class flask_restlib.oauth2.mixins.ScopeMixin¶
Базовые классы:
objectMixin for entities that use scopes.
- class flask_restlib.oauth2.mixins.UserMixin¶
Базовые классы:
flask_login.mixins.UserMixinA mixin for describing a user.
RBAC¶
- class flask_restlib.oauth2.rbac.RoleMixin¶
Базовые классы:
flask_restlib.oauth2.mixins.ScopeMixinA mixin for describing a role that uses scopes.
- get_children() Sequence[flask_restlib.oauth2.rbac.RoleMixin]¶
Returns child roles.
- class flask_restlib.oauth2.rbac.UserMixin¶
Базовые классы:
flask_restlib.oauth2.mixins.ScopeMixin,flask_restlib.oauth2.mixins.UserMixinA mixin for describing a user that uses roles.
- get_roles() Sequence[flask_restlib.oauth2.rbac.RoleMixin]¶
Returns the roles assigned to the user.
Views¶
- class flask_restlib.oauth2.views.AccessTokenView(template_name=None)¶
Базовые классы:
flask_useful.views.MethodViewAccess token request.
- class flask_restlib.oauth2.views.AuthorizeView(template_name=None)¶
Базовые классы:
flask_useful.views.MethodViewApplication authorization.
- class flask_restlib.oauth2.views.IndexView(template_name=None)¶
Базовые классы:
flask_useful.views.MethodViewHome page.
- class flask_restlib.oauth2.views.LoginView(template_name=None)¶
Базовые классы:
flask_useful.views.FormViewAccount authentication.
- form_class¶
alias of
flask_restlib.forms.LoginForm
- form_valid(form: FlaskForm, obj: t.Optional[t.Any] = None) ResponseReturnValue¶
Runs if the form is processed successfully.
- class flask_restlib.oauth2.views.LogoutView(template_name=None)¶
Базовые классы:
flask_useful.views.MethodViewLogout of your account.
- class flask_restlib.oauth2.views.RevokeTokenEndpoint(server)¶
Базовые классы:
authlib.oauth2.rfc7009.revocation.RevocationEndpoint- query_token(token_string: str, token_type_hint: str) Optional[flask_restlib.oauth2.mixins.TokenMixin]¶
Get the token from database/storage by the given token string. Developers should implement this method:
def query_token(self, token_string, token_type_hint): if token_type_hint == 'access_token': return Token.query_by_access_token(token_string) if token_type_hint == 'refresh_token': return Token.query_by_refresh_token(token_string) return Token.query_by_access_token(token_string) or Token.query_by_refresh_token(token_string)
- revoke_token(token: flask_restlib.oauth2.mixins.TokenMixin, request: authlib.oauth2.rfc6749.wrappers.OAuth2Request) None¶
Mark token as revoked. Since token MUST be unique, it would be dangerous to delete it. Consider this situation:
Jane obtained a token XYZ
Jane revoked (deleted) token XYZ
Bob generated a new token XYZ
Jane can use XYZ to access Bob’s resource
It would be secure to mark a token as revoked:
def revoke_token(self, token, request): hint = request.form.get('token_type_hint') if hint == 'access_token': token.access_token_revoked = True else: token.access_token_revoked = True token.refresh_token_revoked = True token.save()
- class flask_restlib.oauth2.views.RevokeTokenView(template_name=None)¶
Базовые классы:
flask_useful.views.MethodViewRevokes a previously issued token.
ORM¶
- class flask_restlib.orm.AbstractQueryAdapter(base_query: Union[flask_restlib.orm.TNativeQuery, flask_restlib.orm.TQueryAdapter])¶
Базовые классы:
Generic[flask_restlib.orm.TNativeQuery]- abstract exists() bool¶
Returns true if a resource with the specified search criteria exists in persistent storage.
- filter(filter_callback: Callable[[Any], Any]) flask_restlib.orm.TQueryAdapter¶
Applies this filter to the current queryset.
- abstract filter_by(**kwargs: Any) flask_restlib.orm.TQueryAdapter¶
Applies these criteria to the current queryset.
- first() Optional[Any]¶
Return the first result of this query or None if the result doesn’t contain any row.
- limit(value: int) flask_restlib.orm.TQueryAdapter¶
Applies a limit on the number of rows selected by the query.
- abstract make_query() flask_restlib.orm.TNativeQuery¶
Creates and returns a native query object.
- offset(value: int) flask_restlib.orm.TQueryAdapter¶
Applies the offset from which the query will select rows.
- one_or_none() Optional[Any]¶
Return at most one result or raise an exception. Returns None if the query selects no rows.
- order_by(column: Union[str, tuple[str, bool]], *columns: Union[str, tuple[str, bool]]) flask_restlib.orm.TQueryAdapter¶
Applies sorting by attribute.
- abstract prepare_query(base_query: flask_restlib.orm.TNativeQuery) flask_restlib.orm.TNativeQuery¶
Processes the constructor’s input argument and returns a native query.
- class flask_restlib.orm.AbstractQueryExpression(expr: Any)¶
Базовые классы:
Generic[flask_restlib.orm.TNativeQuery]An adapter represent that is:
model column that overloads all valid operators;
an expression with which one of the valid operators can be used.
For example:
>>> from flask_restlib import Q, authorization_server >>> model = authorization_server.OAuth2Token >>> token = 'abcde12345' >>> (Q(model.access_token) == token) | (Q(model.refresh_token) == token) <flask_restlib.contrib.sqla.SQLAQueryExpression object at 0x101029dd0>
An instance of the current class is used as a filter for the results of a persistent storage query.
- class flask_restlib.orm.AbstractResourceManager¶
Базовые классы:
Generic[flask_restlib.orm.TModel]Manager for working with REST resources.
- abstract create(model_class: Type[flask_restlib.orm.TModel], data: Union[dict, list[dict]]) Union[flask_restlib.orm.TModel, list[TModel]]¶
Creates and returns a new instance of the resource filled with data.
- abstract delete(resource: flask_restlib.orm.TModel) None¶
Removes the resource from the persistent storage.
- Параметры
resource (object) – The resource instance.
- abstract get(model_class: Type[flask_restlib.orm.TModel], identifier: Union[Any, tuple, dict]) Optional[flask_restlib.orm.TModel]¶
Returns a resource based on the given identifier, or None if not found.
- Параметры
model_class (type) – A reference to the model class that describes the REST resource.
identifier – A scalar, tuple, or dictionary representing the primary key.
Pagination¶
- class flask_restlib.pagination.AbstractPagination(*, default_limit: Optional[int] = None, limit_param_name: Optional[str] = None)¶
Базовые классы:
object- get_limit_param_name() str¶
Returns name of the URL parameter that specifies the number of collection items per page.
- abstract get_total(queryset: flask_restlib.types.TQueryAdapter) int¶
Returns the total number of items in the collection.
- abstract make_headers(queryset: flask_restlib.types.TQueryAdapter, base_url: str) list[tuple[str, str]]¶
Returns HTTP headers with pagination.
- abstract paginate(queryset: flask_restlib.types.TQueryAdapter) flask_restlib.types.TQueryAdapter¶
Applies pagination to the queryset and returns a new queryset.
- class flask_restlib.pagination.LimitOffsetPagination(*, default_limit: Optional[int] = None, limit_param_name: Optional[str] = None, offset_param_name: Optional[str] = None)¶
Базовые классы:
flask_restlib.pagination.AbstractPagination- get_offset_param_name() str¶
Returns name of the URL parameter that specifies the offset from the first item in the collection.
- get_total(queryset: flask_restlib.types.TQueryAdapter) int¶
Returns the total number of items in the collection.
- make_headers(queryset: flask_restlib.types.TQueryAdapter, base_url: str) list[tuple[str, str]]¶
Returns HTTP headers with pagination.
- paginate(queryset: flask_restlib.types.TQueryAdapter) flask_restlib.types.TQueryAdapter¶
Applies pagination to the queryset and returns a new queryset.
Permissions¶
- class flask_restlib.permissions.Permission¶
Базовые классы:
objectA base class from which all permission classes should inherit.
- class flask_restlib.permissions.IsAuthenticated¶
Базовые классы:
flask_restlib.permissions.PermissionAllows access only to authenticated users.
- class flask_restlib.permissions.PublicMethods(methods: Sequence[str])¶
Базовые классы:
flask_restlib.permissions.PermissionAllows public access only for the listed methods.
Routing¶
- class flask_restlib.routing.Route(resource_name: str, view: Union[Callable, flask.views.View], endpoint: Optional[str] = None, *, is_item: bool = False, url_converter: str = 'int', lookup_name: Optional[str] = 'id', url_prefix: str = '')¶
Базовые классы:
objectВ аргумент view можно передать представление на базе функции или класса. Если передано представление на базе класса, то автоматически вызывается метод as_view. Если методу as_view необходимо передать дополнительные аргументы, кроме endpoint, то сделайте это вручную: Route(„users“, UserView.as_view(„users“, *args, **kwargs))
- class flask_restlib.routing.Router(name: str, url_prefix: Optional[str] = None)¶
Базовые классы:
object- add_route(route: flask_restlib.routing.Route) flask_restlib.routing.Route¶
Adds a route for the resource.
Schemas¶
- class flask_restlib.schemas.RestlibSchemaOpts(meta: object, *args: Any, **kwargs: Any)¶
Базовые классы:
flask_restlib.schemas.RestlibMixin.Opts,marshmallow.schema.SchemaOpts
- class flask_restlib.schemas.RestlibSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)¶
Базовые классы:
marshmallow.schema.Schema- OPTIONS_CLASS¶
- opts: SchemaOpts = <flask_restlib.schemas.RestlibSchemaOpts object>¶
- class flask_restlib.schemas.ClientSchema(*, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None)¶
Базовые классы:
marshmallow.schema.Schema
Sorting¶
Types¶
Utilities¶
- flask_restlib.utils.camel_to_list(s: str, lower: bool = False) list[str]¶
Converts a camelcase string to a list.
- flask_restlib.utils.camel_to_snake(name: str) str¶
Converts a camelcase string to a snake case string.
- flask_restlib.utils.snake_to_camel(name: str) str¶
Converts a snake case string to a camelcase string.
Validators¶
Views¶
Contrib¶
SQLAlchemy¶
- flask_restlib.contrib.sqla.create_authorization_code_model(user_model: Type[flask_restlib.oauth2.mixins.UserMixin], client_model: Type[flask_restlib.oauth2.mixins.ClientMixin], table_name: str = 'oauth2_code', is_abstract: bool = False) Type[flask_restlib.oauth2.mixins.AuthorizationCodeMixin]¶
Creates and returns a base abstract class to describe a OAuth2 authorization code.
The name of the new class is OAuth2Code, use it in a relationship or class reference.
- flask_restlib.contrib.sqla.create_client_model(user_model: Type[flask_restlib.oauth2.mixins.UserMixin], table_name: str = 'oauth2_client', is_abstract: bool = False) Type[flask_restlib.oauth2.mixins.ClientMixin]¶
Creates and returns a base abstract class to describe a OAuth2 client.
The name of the new class is OAuth2Client, use it in a relationship or class reference.
- flask_restlib.contrib.sqla.create_role_model(base_model_class: Type, table_name: str = 'oauth2_role', is_abstract: bool = False) Type[flask_restlib.oauth2.rbac.RoleMixin]¶
Creates and returns a base abstract class to describe a role.
The name of the new class is OAuth2Role, use it in a relationship or class reference.
- flask_restlib.contrib.sqla.create_token_model(user_model: Type[flask_restlib.oauth2.mixins.UserMixin], client_model: Type[flask_restlib.oauth2.mixins.ClientMixin], table_name: str = 'oauth2_token', is_abstract: bool = False) Type[flask_restlib.oauth2.mixins.TokenMixin]¶
Creates and returns a base abstract class to describe a OAuth2 token.
The name of the new class is OAuth2Token, use it in a relationship or class reference.
- class flask_restlib.contrib.sqla.SQLAQueryAdapter(base_query: Union[sqlalchemy.orm.query.Query, flask_restlib.contrib.sqla.SQLAQueryAdapter], *, session: sqlalchemy.orm.session.Session)¶
Базовые классы:
flask_restlib.orm.AbstractQueryAdapter[sqlalchemy.orm.query.Query]- exists() bool¶
Returns true if a resource with the specified search criteria exists in persistent storage.
- filter_by(**kwargs: Any) flask_restlib.contrib.sqla.SQLAQueryAdapter¶
Applies these criteria to the current queryset.
- make_query() sqlalchemy.orm.query.Query¶
Creates and returns a native query object.
- order_by(column: Union[str, tuple[str, bool]], *columns: Union[str, tuple[str, bool]]) flask_restlib.contrib.sqla.SQLAQueryAdapter¶
Applies sorting by attribute.
- prepare_query(base_query: sqlalchemy.orm.query.Query) sqlalchemy.orm.query.Query¶
Processes the constructor’s input argument and returns a native query.
- class flask_restlib.contrib.sqla.SQLAResourceManager(session: sqlalchemy.orm.session.Session)¶
Базовые классы:
flask_restlib.orm.AbstractResourceManager[flask_restlib.contrib.sqla.TModel]- create(model_class: Type[flask_restlib.contrib.sqla.TModel], data: Union[dict, list[dict]]) Union[flask_restlib.contrib.sqla.TModel, list[TModel]]¶
Creates and returns a new instance of the resource filled with data.
- delete(resource: flask_restlib.contrib.sqla.TModel) None¶
Removes the resource from the persistent storage.
- Параметры
resource (object) – The resource instance.
- get(model_class: Type[flask_restlib.contrib.sqla.TModel], identifier: Union[Any, tuple, dict]) Optional[flask_restlib.contrib.sqla.TModel]¶
Returns a resource based on the given identifier, or None if not found.
- Параметры
model_class (type) – A reference to the model class that describes the REST resource.
identifier – A scalar, tuple, or dictionary representing the primary key.
- class flask_restlib.contrib.sqla.SQLAFactory(session: Optional[sqlalchemy.orm.session.Session] = None)¶
Базовые классы:
flask_restlib.core.AbstractFactory[flask_restlib.contrib.sqla.SQLAQueryExpression,flask_restlib.contrib.sqla.SQLAQueryAdapter,flask_restlib.contrib.sqla.SQLAResourceManager,flask_restlib.contrib.sqla.SQLAlchemySchema,flask_restlib.contrib.sqla.SQLAlchemySchemaOpts,flask_restlib.contrib.sqla.TModel],Generic[flask_restlib.contrib.sqla.TModel]- create_authorization_code_model(user_model: Type[flask_restlib.oauth2.mixins.UserMixin], client_model: Type[flask_restlib.oauth2.mixins.ClientMixin]) Type[flask_restlib.oauth2.mixins.AuthorizationCodeMixin]¶
Creates and returns the OAuth2 code class.
- create_client_model(user_model: Type[flask_restlib.oauth2.mixins.UserMixin]) Type[flask_restlib.oauth2.mixins.ClientMixin]¶
Creates and returns the OAuth2 client class.
- create_query_adapter(base_query: Any) flask_restlib.contrib.sqla.SQLAQueryAdapter¶
Creates and returns a queryset for retrieving resources from persistent storage.
- create_query_expression(expr: Any) flask_restlib.contrib.sqla.SQLAQueryExpression¶
Creates and returns an adapter for a model attribute.
- Параметры
expr –
orm.AbstractQueryExpressionor native expression.
- create_resource_manager() flask_restlib.contrib.sqla.SQLAResourceManager[flask_restlib.contrib.sqla.TModel]¶
Creates and returns a resource manager instance.
- create_schema(model_class: Type[flask_restlib.contrib.sqla.TModel]) Type[flask_restlib.contrib.sqla.SQLAlchemyAutoSchema]¶
Creates and returns an automatic schema class.
- Параметры
model_class – A reference to the model class that describes the REST resource.
- create_token_model(user_model: Type[flask_restlib.oauth2.mixins.UserMixin], client_model: Type[flask_restlib.oauth2.mixins.ClientMixin]) Type[flask_restlib.oauth2.mixins.TokenMixin]¶
Creates and returns the OAuth2 token class.
- get_auto_schema_class() Type[flask_restlib.contrib.sqla.SQLAlchemyAutoSchema]¶
Returns a reference to the base class of the schema used in serialization and validation.
- get_auto_schema_options_class() Type[flask_restlib.contrib.sqla.SQLAlchemyAutoSchemaOpts]¶
Returns a reference to the base auto schema options class.
MongoEngine¶
- flask_restlib.contrib.mongoengine.create_authorization_code_model(user_model: Type[flask_restlib.oauth2.mixins.UserMixin], client_model: Type[flask_restlib.oauth2.mixins.ClientMixin], is_abstract: bool = False) Type[flask_restlib.oauth2.mixins.AuthorizationCodeMixin]¶
Creates and returns a base abstract class to describe a OAuth2 authorization code.
The name of the new class is OAuth2Code, use it in a relationship or class reference.
- flask_restlib.contrib.mongoengine.create_client_model(user_model: Type[flask_restlib.oauth2.mixins.UserMixin], is_abstract: bool = False) Type[flask_restlib.oauth2.mixins.ClientMixin]¶
Creates and returns a base abstract class to describe a OAuth2 client.
The name of the new class is OAuth2Client.
- flask_restlib.contrib.mongoengine.create_token_model(user_model: Type[flask_restlib.oauth2.mixins.UserMixin], client_model: Type[flask_restlib.oauth2.mixins.ClientMixin], is_abstract: bool = False) Type[flask_restlib.oauth2.mixins.TokenMixin]¶
Creates and returns a base abstract class to describe a OAuth2 token.
The name of the new class is OAuth2Token, use it in a relationship or class reference.
- class flask_restlib.contrib.mongoengine.OAuth2Role(*args, **values)¶
Базовые классы:
flask_restlib.oauth2.rbac.RoleMixin,flask_mongoengine.Document- exception DoesNotExist¶
Базовые классы:
mongoengine.errors.DoesNotExist
- exception MultipleObjectsReturned¶
Базовые классы:
mongoengine.errors.MultipleObjectsReturned
- class flask_restlib.contrib.mongoengine.MongoQueryAdapter(base_query: Union[flask_restlib.orm.TNativeQuery, flask_restlib.orm.TQueryAdapter])¶
Базовые классы:
flask_restlib.orm.AbstractQueryAdapter[mongoengine.queryset.base.BaseQuerySet]- exists() bool¶
Returns true if a resource with the specified search criteria exists in persistent storage.
- filter_by(**kwargs: Any) flask_restlib.contrib.mongoengine.MongoQueryAdapter¶
Applies these criteria to the current queryset.
- make_query() mongoengine.queryset.base.BaseQuerySet¶
Creates and returns a native query object.
- order_by(column: Union[str, tuple[str, bool]], *columns: Union[str, tuple[str, bool]]) flask_restlib.contrib.mongoengine.MongoQueryAdapter¶
Applies sorting by attribute.
- prepare_query(base_query: mongoengine.queryset.base.BaseQuerySet) mongoengine.queryset.base.BaseQuerySet¶
Processes the constructor’s input argument and returns a native query.
- class flask_restlib.contrib.mongoengine.MongoResourceManager¶
Базовые классы:
flask_restlib.orm.AbstractResourceManager[flask_restlib.contrib.mongoengine.TDocument]- create(model_class: Any, data: Union[dict, list[dict]]) Any¶
Creates and returns a new instance of the resource filled with data.
- delete(resource: Any) None¶
Removes the resource from the persistent storage.
- Параметры
resource (object) – The resource instance.
- get(model_class: Type[Any], identifier: Union[Any, tuple, dict]) Optional[Any]¶
Returns a resource based on the given identifier, or None if not found.
- Параметры
model_class (type) – A reference to the model class that describes the REST resource.
identifier – A scalar, tuple, or dictionary representing the primary key.
- class flask_restlib.contrib.mongoengine.MongoEngineFactory¶
Базовые классы:
flask_restlib.core.AbstractFactory[flask_restlib.contrib.mongoengine.MongoQueryExpression,flask_restlib.contrib.mongoengine.MongoQueryAdapter,flask_restlib.contrib.mongoengine.MongoResourceManager,flask_restlib.contrib.mongoengine.MongoSchema,flask_restlib.contrib.mongoengine.MongoSchemaOpts,flask_restlib.contrib.mongoengine.TDocument],Generic[flask_restlib.contrib.mongoengine.TDocument]- create_authorization_code_model(user_model: Type[flask_restlib.oauth2.mixins.UserMixin], client_model: Type[flask_restlib.oauth2.mixins.ClientMixin]) Type[flask_restlib.oauth2.mixins.AuthorizationCodeMixin]¶
Creates and returns the OAuth2 code class.
- create_client_model(user_model: Type[flask_restlib.oauth2.mixins.UserMixin]) Type[flask_restlib.oauth2.mixins.ClientMixin]¶
Creates and returns the OAuth2 client class.
- create_query_adapter(base_query: Any) flask_restlib.contrib.mongoengine.MongoQueryAdapter¶
Creates and returns a queryset for retrieving resources from persistent storage.
- create_query_expression(expr: Any) flask_restlib.contrib.mongoengine.MongoQueryExpression¶
Creates and returns an adapter for a model attribute.
- Параметры
expr –
orm.AbstractQueryExpressionor native expression.
- create_resource_manager() flask_restlib.contrib.mongoengine.MongoResourceManager[flask_restlib.contrib.mongoengine.TDocument]¶
Creates and returns a resource manager instance.
- create_schema(model_class: Type[flask_restlib.contrib.mongoengine.TDocument]) Type[flask_restlib.contrib.mongoengine.MongoAutoSchema]¶
Creates and returns an automatic schema class.
- Параметры
model_class – A reference to the model class that describes the REST resource.
- create_token_model(user_model: Type[flask_restlib.oauth2.mixins.UserMixin], client_model: Type[flask_restlib.oauth2.mixins.ClientMixin]) Type[flask_restlib.oauth2.mixins.TokenMixin]¶
Creates and returns the OAuth2 token class.
- get_auto_schema_class() Type[flask_restlib.contrib.mongoengine.MongoAutoSchema]¶
Returns a reference to the base class of the schema used in serialization and validation.
- get_auto_schema_options_class() Type[flask_restlib.contrib.mongoengine.MongoAutoSchemaOpts]¶
Returns a reference to the base auto schema options class.