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.

Параметры

exprorm.AbstractQueryExpression or 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.

abstract get_schema_class() Type[flask_restlib.core.TSchema]

Returns a reference to the base class of the schema used in serialization and validation.

abstract get_schema_options_class() Type[flask_restlib.core.TSchemaOpts]

Returns a reference to the base 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.RestlibError

The 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.RestlibError

There 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

class flask_restlib.exceptions.MultipleResourcesFound(message: Optional[str] = None, detail: Optional[dict] = None)

Базовые классы: flask_restlib.exceptions.RestlibError

class flask_restlib.exceptions.NoResourcesFound(message: Optional[str] = None, detail: Optional[dict] = None)

Базовые классы: flask_restlib.exceptions.RestlibError

Filters

class flask_restlib.filters.AbstractFilter

Базовые классы: object

The 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.

get_input_data() dict

Returns the input used for filtering.

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.FlaskForm

Login 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

abstract add(etag_string: str) None

Adds ETag to fast cache.

check() bool

Returns true if one of given ETags exists in the fast cache otherwise false.

abstract clear() None

Removes all ETags associated with the resource from the fast cache.

abstract in_cache(etag_string: str) bool

Returns true if given ETag is in the fast cache otherwise false.

class flask_restlib.http.HttpCache(*, methods_support_caching: Optional[set[str]] = None, methods_need_etag: Optional[set[str]] = None)

Базовые классы: flask_restlib.http.AbstractHttpCache

add(etag_string: str) None

Adds ETag to fast cache.

clear() None

Removes all ETags associated with the resource from the fast cache.

in_cache(etag_string: str) bool

Returns true if given ETag is in the fast cache otherwise false.

class flask_restlib.http.HTTPMethodOverrideMiddleware(app: WSGIApplication)

Базовые классы: object

https://flask.palletsprojects.com/en/2.1.x/patterns/methodoverrides/

Mixins

OAuth2

Authorization Server

class flask_restlib.oauth2.authorization_server.AuthorizationServer(app: Optional[flask.app.Flask] = None, *, user_model: Type[flask_restlib.oauth2.mixins.UserMixin], client_model: Type[flask_restlib.oauth2.mixins.ClientMixin], token_model: Type[flask_restlib.oauth2.mixins.TokenMixin], authorization_code_model: Type[flask_restlib.oauth2.mixins.AuthorizationCodeMixin], query_client: Optional[Callable] = None, query_supported_scopes: Optional[Callable] = None, save_token: Optional[Callable] = None)

Базовые классы: authlib.integrations.flask_oauth2.authorization_server.AuthorizationServer

generate_token(grant_type: str, client: flask_restlib.oauth2.mixins.ClientMixin, user: Optional[flask_restlib.oauth2.mixins.UserMixin] = None, scope: Optional[str] = None, expires_in: Optional[int] = None, include_refresh_token: bool = True) dict[str, Any]

Generate the token dict.

Параметры
  • grant_type – current requested grant_type.

  • client – the client that making the request.

  • user – current authorized user.

  • expires_in – if provided, use this value as expires_in.

  • scope – current requested scope.

  • include_refresh_token – should refresh_token be included.

Результат

Token dict

get_registered_grants(*, only_public: bool = False, only_confidential: bool = False) dict[str, Type[authlib.oauth2.rfc6749.grants.base.BaseGrant]]

Returns registered grants.

get_supported_scopes() set[Any]

Returns set of supported scopes by this authorization server.

init_app(app: flask.app.Flask, *, query_client: Optional[Callable] = None, save_token: Optional[Callable] = None) None

Initialize later with Flask app instance.

register_grant(grant_cls: Type[authlib.oauth2.rfc6749.grants.base.BaseGrant], extensions: Optional[list] = None) None

Register a grant class into the endpoint registry.

class flask_restlib.oauth2.authorization_server.BearerTokenValidator(realm=None, **extra_attributes)

Базовые классы: authlib.oauth2.rfc6750.validator.BearerTokenValidator

authenticate_token(token_string: str) Optional[flask_restlib.oauth2.mixins.TokenMixin]

A method to query token from database with the given token string. Developers MUST re-implement this method. For instance:

def authenticate_token(self, token_string):
    return get_token_from_database(token_string)
Параметры

token_string – A string to represent the access_token.

Результат

token

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 called redirect_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_method defined 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_types column 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_uris column:

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_types column 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_id is saved on token table:

def check_client(self, client):
    return self.client_id == client.client_id
Результат

bool

get_access_token() str

Returns access token string.

get_client() flask_restlib.oauth2.mixins.ClientMixin

Returns the client to which the token was issued.

get_expires_at() int

Returns timestamp indicating when this token will expire.

get_expires_in() int

A method to get the expires_in value of the token. e.g. the column is called expires_in:

def get_expires_in(self):
    return self.expires_in
Результат

timestamp int

get_refresh_token() str

Returns refresh token 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_token_type() str

Returns access token type.

get_user() flask_restlib.oauth2.mixins.UserMixin

Returns token owner.

is_expired() bool

A method to define if this token is expired. For instance, there is a column expired_at in the table:

def is_expired(self):
    return self.expired_at < now
Результат

boolean

is_refresh_token_valid() bool

Returns true if the token is not expired, false otherwise.

is_revoked() bool

Returns true if the token has been revoked, false otherwise.

class flask_restlib.oauth2.mixins.ScopeMixin

Базовые классы: object

Mixin for entities that use scopes.

get_allowed_scope(scope: str) str

Returns the allowed scopes from the given scope.

get_scope() str

Returns string containing a space-separated list of scope values.

get_scopes() set[Any]

Returns list of scope values.

class flask_restlib.oauth2.mixins.UserMixin

Базовые классы: flask_login.mixins.UserMixin

A mixin for describing a user.

change_password(value: str) None

Changes the current password to passed.

check_password(password: str) bool

Returns true if the password is valid, false otherwise.

classmethod find_by_username(username: str) Any

Returns the user with passed username, or None.

get_user_id() Any

Returns user id, requires Authlib.

RBAC

class flask_restlib.oauth2.rbac.RoleMixin

Базовые классы: flask_restlib.oauth2.mixins.ScopeMixin

A mixin for describing a role that uses scopes.

get_children() Sequence[flask_restlib.oauth2.rbac.RoleMixin]

Returns child roles.

get_description() str

Returns the full description of the role.

get_name() str

Returns the programmatic name of the role, which is unique.

get_scopes() set[Any]

Returns the scopes of the role.

class flask_restlib.oauth2.rbac.UserMixin

Базовые классы: flask_restlib.oauth2.mixins.ScopeMixin, flask_restlib.oauth2.mixins.UserMixin

A mixin for describing a user that uses roles.

get_roles() Sequence[flask_restlib.oauth2.rbac.RoleMixin]

Returns the roles assigned to the user.

get_scopes() set[Any]

Returns the scopes assigned to the user.

Views

class flask_restlib.oauth2.views.AccessTokenView(template_name=None)

Базовые классы: flask_useful.views.MethodView

Access token request.

class flask_restlib.oauth2.views.AuthorizeView(template_name=None)

Базовые классы: flask_useful.views.MethodView

Application authorization.

class flask_restlib.oauth2.views.IndexView(template_name=None)

Базовые классы: flask_useful.views.MethodView

Home page.

class flask_restlib.oauth2.views.LoginView(template_name=None)

Базовые классы: flask_useful.views.FormView

Account 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.MethodView

Logout 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:

  1. Jane obtained a token XYZ

  2. Jane revoked (deleted) token XYZ

  3. Bob generated a new token XYZ

  4. 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.MethodView

Revokes 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 all() list

Returns the results represented by this query as a list.

abstract count() int

Returns the number of rows that should be returned from the query.

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() Any

Return exactly one result or raise an exception.

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.

to_native(expr: Any) flask_restlib.orm.TNativeQuery

Retrieves a native expression from the adapter and returns it.

class flask_restlib.orm.AbstractResourceManager

Базовые классы: Generic[flask_restlib.orm.TModel]

Manager for working with REST resources.

abstract commit() None

Saves the changes to persistent storage.

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.

Параметры
  • model_class – A reference to the model class that describes the REST resource.

  • data (dict|list) – Resource attributes.

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.

populate_obj(resource: flask_restlib.orm.TModel, attributes: dict) None

Populates the attributes of the given resource with data from the given attributes argument.

Параметры
  • resource (object) – The resource instance.

  • attributes (dict) – Resource attributes with new values.

abstract rollback() None

Rollback the current transaction in progress.

abstract update(resource: flask_restlib.orm.TModel, attributes: dict) flask_restlib.orm.TModel

Updates the resource with the values of the passed attributes.

Параметры
  • resource (object) – The resource instance.

  • attributes (dict) – Resource attributes with new values.

Pagination

class flask_restlib.pagination.AbstractPagination(*, default_limit: Optional[int] = None, limit_param_name: Optional[str] = None)

Базовые классы: object

get_default_limit() int

Returns default number of collection items per page.

get_limit() int

Returns the number of collection items per page.

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() int

Returns offset from the first item in the collection.

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

Базовые классы: object

A base class from which all permission classes should inherit.

abstract check_permission(view: Union[Callable, flask.views.View], resource: Optional[Any] = None) None

Checks if permission was granted, otherwise raises any exception.

If passed resource then checks if permission for the object was granted.

class flask_restlib.permissions.IsAuthenticated

Базовые классы: flask_restlib.permissions.Permission

Allows access only to authenticated users.

check_permission(view: Union[Callable, flask.views.View], resource: Optional[Any] = None) None

Checks if permission was granted, otherwise raises any exception.

If passed resource then checks if permission for the object was granted.

class flask_restlib.permissions.PublicMethods(methods: Sequence[str])

Базовые классы: flask_restlib.permissions.Permission

Allows public access only for the listed methods.

check_permission(view: Union[Callable, flask.views.View], resource: Optional[Any] = None) None

Checks if permission was granted, otherwise raises any exception.

If passed resource then checks if permission for the object was granted.

class flask_restlib.permissions.TokenHasScope(scope: Optional[Union[str, list]] = None, optional: bool = False)

Базовые классы: flask_restlib.permissions.Permission

The TokenHasScope permission class allows access when the current access token has been authorized for all the scopes.

check_permission(view: Union[Callable, flask.views.View], resource: Optional[Any] = None) None

Checks if permission was granted, otherwise raises any exception.

If passed resource then checks if permission for the object was granted.

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))

get_rule(replace_lookup_name: Optional[str] = None) str

Returns the URL rule as a string.

has_lookup() bool

Returns true if the route uses an identifier for searching.

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.RestlibMixin

Базовые классы: object

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

alias of flask_restlib.schemas.RestlibSchemaOpts

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

class Meta

Базовые классы: object

Sorting

class flask_restlib.sorting.SortHandler(sorting_fields: Sequence[str], sort_param_name: str = '')

Базовые классы: object

execute(q: flask_restlib.types.TQueryAdapter) flask_restlib.types.TQueryAdapter

Applies a sort to the given queryset and returns new queryset.

Параметры

q – current queryset.

property sort_param_name: str

Returns the name of the URL parameter that is used for 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.

flask_restlib.utils.iter_to_scope(scope: Iterable[str]) str

Convert a list of scopes to a space separated string.

flask_restlib.utils.scope_to_set(scope: str) set[str]

Convert a space separated string to a set of scopes.

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.

Параметры
  • user_model – reference to the user model class.

  • client_model – reference to the client model class.

  • table_name (str) – table name in the database.

  • is_abstract (bool) – make the model abstract, by default False.

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.

Параметры
  • user_model – reference to the user model class.

  • table_name (str) – table name in the database.

  • is_abstract (bool) – make the model abstract, by default False.

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.

Параметры
  • base_model_class – a base class for declarative class definitions.

  • table_name (str) – table name in the database.

  • is_abstract (bool) – make the model abstract, by default False.

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.

Параметры
  • user_model – reference to the user model class.

  • client_model – reference to the client model class.

  • table_name (str) – table name in the database.

  • is_abstract (bool) – make the model abstract, by default False.

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]

all() list

Returns the results represented by this query as a list.

count() int

Returns the number of rows that should be returned from the 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]

commit() None

Saves the changes to persistent storage.

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.

Параметры
  • model_class – A reference to the model class that describes the REST resource.

  • data (dict|list) – Resource attributes.

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.

rollback() None

Rollback the current transaction in progress.

update(resource: flask_restlib.contrib.sqla.TModel, attributes: dict) flask_restlib.contrib.sqla.TModel

Updates the resource with the values of the passed attributes.

Параметры
  • resource (object) – The resource instance.

  • attributes (dict) – Resource attributes with new values.

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.

Параметры

exprorm.AbstractQueryExpression or 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.

get_schema_class() Type[flask_restlib.contrib.sqla.SQLAlchemySchema]

Returns a reference to the base class of the schema used in serialization and validation.

get_schema_options_class() Type[flask_restlib.contrib.sqla.SQLAlchemySchemaOpts]

Returns a reference to the base 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.

Параметры
  • user_model – reference to the user model class.

  • client_model – reference to the client model class.

  • table_name (str) – table name in the database.

  • is_abstract (bool) – make the model abstract, by default False.

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.

Параметры
  • user_model – reference to the user model class.

  • table_name (str) – table name in the database.

  • is_abstract (bool) – make the model abstract, by default False.

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.

Параметры
  • user_model – reference to the user model class.

  • client_model – reference to the client model class.

  • table_name (str) – table name in the database.

  • is_abstract (bool) – make the model abstract, by default False.

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]

all() list

Returns the results represented by this query as a list.

count() int

Returns the number of rows that should be returned from the query.

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]

commit() None

Saves the changes to persistent storage.

create(model_class: Any, data: Union[dict, list[dict]]) Any

Creates and returns a new instance of the resource filled with data.

Параметры
  • model_class – A reference to the model class that describes the REST resource.

  • data (dict|list) – Resource attributes.

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.

rollback() None

Rollback the current transaction in progress.

update(resource: Any, attributes: dict) Any

Updates the resource with the values of the passed attributes.

Параметры
  • resource (object) – The resource instance.

  • attributes (dict) – Resource attributes with new values.

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.

Параметры

exprorm.AbstractQueryExpression or 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.

get_schema_class() Type[flask_restlib.contrib.mongoengine.MongoSchema]

Returns a reference to the base class of the schema used in serialization and validation.

get_schema_options_class() Type[flask_restlib.contrib.mongoengine.MongoSchemaOpts]

Returns a reference to the base schema options class.