References — backo 0.0.1 documentation

# References

Module backo. export all classes

class backo.Action(schema: dict, on_trig: Callable, **kwargs)

  Bases: `Dict`

  The action to do on a collection

  Parameters:

    - schema (dict) – The data schema needed for this action (see Dict <https://stricto.readthedocs.io/en/latest/api_reference.html#stricto.Dict>)

    - on_trig (Callable) – the function to trig on the action

    - **kwargs – see https://stricto.readthedocs.io/en/latest/api_reference.html#stricto.Dict - can_see= `[func]|bool` – a function to say if this action exists - can_execute= `[func]|bool` – a function to say if the `CurrentUser` can execute this action.

      from backo import Item, Collection, Backoffice, Action, Ref, DBMongoConnector

      # example
      book_item = Item({
          "title": String(),
          "subtitle": String(),
          "author": Ref(coll="authors", field="$.books", required=True),
          "score": Float( default=5.0 )
          "number_of_voter" : Int(default=0)
      })

      def do_vote(action, o):
          o.score = (o.score * o.number_of_voter + action.score) / ( o.number_of_voter + 1 )
          o.number_of_voter += 1

      vote_action = Action( {
          "score" : Float( max=10.0, min=0.0 )
      }, do_vote)

      database_for_books = DBMongoConnector( connection_string="mongodb://localhost:27017/bookcase" )
      books = Collection( "books", book_item, database_for_books )
      books.register_action( "vote", vote_action )

      my_bookstore = Backoffice("bookstore")
      my_bookstore.register_collection(books)
      # ...

  go(o: Item) → None

    > Launch the action

    elf,

      object is the object (if exists)

      meta private:

class backo.Backoffice(name: str)

  Bases: `object`

  Backoffice is tha application itself.

  Parameters:

    name (str) – A name for the application

      from backo import Backoffice

      # example
      my_app = Backoffice("customer_app")

  add_collection(coll: Collection) → None

    See `register_collection()`

  add_routes(flask_app: Flask, prefix: str = '', jwt_auth=None) → None

    Add all routes to flask application

    Parameters:

      - flask_app (Flask) – The Flask object

      - prefix (str) – an optional prefix to the path

      - jwt_auth – The token function

  register_collection(coll: Collection) → None

    Register a collection into this backoffice

    Parameters:

      coll (Collection) – The collection to add.

    See `Collection`

class backo.Collection(name, model: Item, db_handler, **kwargs)

  Bases: `object`

  The Collection refer to a “table”

  A collection is the main object in backo. It contains

    - an `Item` = the description of the object structure

    - an `DBConnector` = the database connector to say how and where to save the object

    - some `Selection` = some preset select for this collection

    - some `Action` = a list of actions to do on this collection

  A collection mus by registered into a `Backoffice` with `Backoffice.register_collection()`

  Parameters:

    - name – The collection name

    - model (Item) – The description of the structure (an Item)

    - db_handler (DBConnector) – The database handler

    - **kwargs –

      - refuse_filter= `func` – not used yet

      - can_read= `[func]|bool` – a function to say if the `CurrentUser` can read this collection

      - can_create= `[func]|bool` – a function to say if the `CurrentUser` can create an `Item` in this collection

      - can_delete= `[func]|bool` – a function to say if the `CurrentUser` can delete an `Item` in this collection

      - can_modify= `[func]|bool` – a function to say if the `CurrentUser` can modify an `Item` in this collection

      from backo import Item, Collection, Backoffice, , DBMongoConnector

      # example
      book_item = Item({
          "title": String(),
          "subtitle": String(),
          "author": Ref(collection="authors", field="$.books", required=True),
      })

      database_for_books = DBMongoConnector( connection_string="mongodb://localhost:27017/bookcase" )
      books = Collection( "books", book_item, database_for_books )

      my_bookstore = Backoffice("bookstore")
      my_bookstore.register_collection(books)
      # ...

  action_go(_action_name: str, _id: str)

    _summary_

    Parameters:

      _id (str) – The _id

    Raises:

      Error – _description_

    Returns:

      _description_

    Return type:

      _type_

  add_action(name: str, action: Action)

    See `register_action()`

  create(obj: dict, **kwargs) → Item

    Create and save an item into the DB

    Parameters:

      - obj (dict) – The json object struture to create

      - **kwargs –

        - transaction_id= `int` – the current transaction_id (in case of rollback)

        - m_path= `[str]` – the modification path, to to avoid loop with references

    Returns:

      an empty Item

    Return type:

      Item

  get_by_id(_id: str) → Item

    Return an object by Id.

    Parameters:

      _id (str) – the _id of the Item you want

    Returns:

      The item

    Return type:

      Item

  get_other_collection(name) → Self

    Return another collection (used by `Ref` and `RefsList`)

    Parameters:

      name – the name of the collection you want

    Returns:

      the collection

    Return type:

      Self

  new_item() → Item

    Return an empty `Item`

    Returns:

      an empty Item

    Return type:

      Item

  register_action(name: str, action: Action)

    Register an action to this collection

    Parameters:

      - name (str) – The name of the action

      - action (`Action`) – the `Action` to register

  register_selection(selection_name: str, selection: Selection) → None

    Register a selction to this collection

    Parameters:

      - name (str) – The name of the selection

      - action (`Selection`) – the `Selection` to register

  select(filter_for_selection: dict) → list[Item]

    Do a selection directly with a filter

    Parameters:

      filter_for_selection (dict) – a filter

    Returns:

      a list of Items

    Return type:

      list[Item]

  select_one(filter_for_selection: dict) → Item

    select one item (if only one)

    Parameters:

      filter_for_selection (dict) – a filter

    Returns:

      The one Item matching the filter

    Return type:

      Item

class backo.CurrentUser(**kwargs)

  Bases: `Dict`

  the current connected user object

  the current user is a Dict with

    - _id (String) : The _id of the user

    - login (String) : The login as a string

    - roles (List of String) : The list of roles for this user. A role is a string which can be used for rights.

  Parameters:

    **kwargs – see https://stricto.readthedocs.io/en/latest/api_reference.html#stricto.Dict

  has_role(role: str | list[str]) → bool

    Return if the currentUser has the role given in param

    Parameters:

      role (str or list[str]) – the role

    Returns:

      a boolean if the user as the role has the role

    Return type:

      bool

        # example
        if current_user.has_role( "Admin" ):
            return True
        else:
            return False

  is_anonymous() → bool

    Return True if the current_user is ANONYMOUS

    Returns:

      the result of the check anonymous

    Return type:

      bool

class backo.Item(schema: dict, **kwargs)

  Bases: `Dict`

  The description of the object of a collection

  Parameters:

    - schema (dict) – its schema (see Dict <https://stricto.readthedocs.io/en/latest/api_reference.html#stricto.Dict>)

    - **kwargs – see https://stricto.readthedocs.io/en/latest/api_reference.html#stricto.Dict

      from backo import Item, Collection, Backoffice, DBMongoConnector

      # example
      book = Item({
          "title": String(),
          "subtitle": String(),
          "author": Ref(coll="authors", field="$.books", required=True),
          "pages": Int()
      })

      database_for_books = DBMongoConnector( connection_string="mongodb://localhost:27017/bookcase" )
      books = Collection( book, database_for_books )

      bookstore = Backoffice("bookstore")
      bookstore.register_collection(books)
      # ...

  create(obj: dict, **kwargs)

    Create and save an object into the DB

    Parameters:

      - obj (dict) – The json object struture to create

      - **kwargs –

        - transaction_id= `int` – the current transaction_id (in case of rollback)

        - m_path= `[str]` – the modification path, to to avoid loop with references

  delete(**kwargs) → None

    delete the object in the database

    Parameters:

      **kwargs –

      - transaction_id= `int` – the current transaction_id (in case of rollback)

      - m_path= `[str]` – the modification path, to to avoid loop with references

  load(_id: str, **kwargs) → None

    Read in the database by Id and fill the Data

    Parameters:

      - _id (str) – The _id to load.

      - **kwargs –

        - transaction_id= `int` – the current transaction_id (in case of rollback)

        - m_path= `[str]` – the modification path, to to avoid loop with references

  reload(**kwargs) → None

    Reload from DB the object (in case of changement)

    Parameters:

      **kwargs –

      - transaction_id= `int` – the current transaction_id (in case of rollback)

      - m_path= `[str]` – the modification path, to to avoid loop with references

  save(**kwargs) → None

    save the object in the database.

    Parameters:

      **kwargs –

      - transaction_id= `int` – the current transaction_id (in case of rollback)

      - m_path= `[str]` – the modification path, to to avoid loop with references

## Ref & RefsList

class backo.DeleteStrategy(*values)

  Bases: `Enum`

  Specifics strategy for deletion for `RefsList`

  when the user want to delete the object, if the object contains a `RefsList`. Say how to handle the deletion

  > - `MUST_BE_EMPTY` = The RefsList must be empty otherwise the delete action will raise an error.

  > - `DELETE_REFERENCED_ITEMS` = All objects targeted with this RefsList will be deleted too. Caution !

  > - `UNLINK_REFERENCED_ITEMS` = The reverse field of all objects targeted with this RefsList will be cleaned

class backo.FillStrategy(*values)

  Bases: `Enum`

  Specifics strategy for fill RefsList in case of one_to_many or many_to_many links

  - `FILL` = The reverse is a List of _ids. Usefull to manage which is pointing to me.

  - `NOT_FILL` = Whe don’t want to fill because the list is to big (for example person -> nationality) but is important to keep the information of this link.

class backo.Ref(**kwargs)

  Bases: `String`

  Ref 0 or 1 to many to another `Collection`

  Parameters:

    **kwargs –

    - collection|coll= `str` – The target collection

    - reverse|rev|field= `str` – The field in the target collection which reference my collection. Must be a RFC 9535 path (https://datatracker.ietf.org/doc/rfc9535/)

      from backo import Item, Ref, RefsList

      # example
      book_item = Item({
          "title": String(),
          "author": Ref(collection="authors", field="$.books", required=True),
      })
      author_item = Item({
          "name": String(),
          "surname": String(),
          "books": RefsList(collection="books", field="$.author"),
      })

      books = Collection( "books", book_item, database_for_books )
      authors = Collection( "authors", author_item, database_for_authors )

      my_bookstore = Backoffice("bookstore")
      my_bookstore.register_collection(books)
      my_bookstore.register_collection(authors)

class backo.RefsList(**kwargs)

  Bases: `List`

  Ref 0 or 1 to many to another `Collection`

  Parameters:

    **kwargs –

    - collection|coll= `str` – The target collection

    - reverse|rev|field= `str` – The field in the target collection which reference my collection. Must be a RFC 9535 path (https://datatracker.ietf.org/doc/rfc9535/)

    - on_delete|ods= `DeleteStrategy` – The deletion strategy `DeleteStrategy`. By default =``DeleteStrategy.MUST_BE_EMPTY``

      from backo import Item, Ref, RefsList, DeleteStrategy

      # example
      book_item = Item({
          "title": String(),
          "author": Ref(collection="authors", field="$.books", required=True),
      })
      author_item = Item({
          "name": String(),
          "surname": String(),
          "books": RefsList(collection="books", field="$.author", ods=DeleteStrategy.DELETE_REFERENCED_ITEMS),
      })

      books = Collection( "books", book_item, database_for_books )
      authors = Collection( "authors", author_item, database_for_authors )

      my_bookstore = Backoffice("bookstore")
      my_bookstore.register_collection(books)
      my_bookstore.register_collection(authors)

## DBconnector

class backo.DBConnector(**kwargs)

  Bases: `object`

  Database Connector

  This is the way to save / store / retrieve objects

  Parameters:

    **kwargs –

    - restriction= `func` – not used yet

  create(o: dict) → str

    Create the object into the DB and return the _id

    Parameters:

      o (dict) – The object given (json format)

    Raises:

      Error – Raise an error ErrorType.NOT_IMPLEMENTED or any db error

  delete_by_id(_id: str)

    The _id to delete on the db

    Parameters:

      _id (str) – the _id

    Raises:

      Error – Raise an error ErrorType.NOT_IMPLEMENTED or any db error

  drop()

    Drop the collection

    Mainly used in test

    Raises:

      Error – Raise an error ErrorType.NOT_IMPLEMENTED or any db error

  generate_id(o: dict) → str

    The function to generate an Id.

    Mainly, not used, because the database itself do the job (like mongo). But for other cases, you must generate by yourself the uniq _id for the object

    Parameters:

      o (dict) – The object given (json format)

    Returns:

      an Id

    Return type:

      str

  get_by_id(_id: str) → dict

    get an object by _id in the DB and return it

    Parameters:

      _id (str) – the _id

    Returns:

      The object (json format)

    Return type:

      dict

    Raises:

      Error – Raise an error ErrorType.NOT_IMPLEMENTED or any db error

  save(_id: str, o: dict)

    Save the objet

    Parameters:

      - _id (str) – the _id of this object

      - o (dict) – The object given (json format)

    Raises:

      Error – Raise an error ErrorType.NOT_IMPLEMENTED or any db error

  select(select_filter, projection: dict = {}, page_size: int = 0, num_of_element_to_skip: int = 0, sort_object: dict = {})

    Select from filter in the DB and return a list of dicts, with pagination

    Parameters:

      - select_filter – The filter for selection (depends on DB types)

      - projection (dict) – The list of elements we want for each object

      - page_size (int) – number of elements per page

      - num_of_element_to_skip (int) – number of element to skip from beginning

      - sort_object (dict) – Soon

    Raises:

      Error – Raise an error ErrorType.NOT_IMPLEMENTED or any db error

class backo.DBMongoConnector(**kwargs)

  Bases: `DBConnector`

  Mongodb database Connector

  This is the way to save / store / retrieve objects in a mongodb

  Parameters:

    **kwargs –

    - restriction= `func` – not used yet

    - all other params are passed to `Mongoclient`

  close()

    Close the mongodb connection

    Raises:

      Error – Raise an error ErrorType.MONGO_CONNECT_ERROR in case of database Error

  connect()

    Try to make a connection to the mongodb

    Raises:

      Error – Raise an error ErrorType.MONGO_CONNECT_ERROR in case of database Error

  create(o: dict)

    See `DBConnector.create()`

  delete_by_id(_id: str)

    See `DBConnector.delete_by_id()`

  drop()

    See `DBConnector.drop()`

    Raises:

      Error – Raise an error ErrorType.MONGO_CONNECT_ERROR in case of database Error

  generate_id(o)

    Do not create _id by ourself. mongo will do the job

  get_by_id(_id: str)

    See `DBConnector.get_by_id()`

  save(_id: str, o: dict)

    See `DBConnector.save()`

  select(select_filter, projection={}, page_size=0, num_of_element_to_skip=0, sort_object={'_id': 1})

    See `DBConnector.select()`

    Parameters:

      select_filter (dict ( a mongodb fliter syntax )) – The filter for selection

class backo.DBYmlConnector(**kwargs)

  Bases: `DBConnector`

  Yaml files database Connector

  This is the way to save / store / retrieve objects in yaml files

  Parameters:

    **kwargs –

    - path= `str` – The directory to store yaml files

  create(o: dict) → str

    See `DBConnector.create()`

  delete_by_id(_id: str) → bool

    See `DBConnector.delete_by_id()`

  drop() → None

    See `DBConnector.drop()`

  get_by_id(_id: str) → dict

    See `DBConnector.get_by_id()`

  save(_id: str, o: dict) → None

    See `DBConnector.save()`

  select(select_filter, projection={}, page_size=0, num_of_element_to_skip=0, sort_object={'_id': 1}) → list

    See `DBConnector.select()`

    Params `select_filter` and `projection` are not used