Skip to main content

A framework designed to assist in using databases and compatible with feliz framework

Project description

feliz_db

An ODM / ORM designed to assist in querying data from some kinds of database

Environment

  • Python 3.9 or higher

Installation

pip install feliz_db

Postgres Tools

PostgresHandler

Initialization

from feliz_db.postgres_tools import PostgresHandler

configs = {
    "host": "localhost",
    "port": 5432,
    "database": "postgres",
    "username": "postgres",
    "password": "postgres"
}

DH = PostgresHandler(**configs)

Users can use the add_data, get_data, update_data, and delete_data methods to add, update, and delete data from a table.

All methods will return a dictionary with the following keys:

  • indicator: The indicator of the operation. It will be True if the operation is successful, otherwise it will be False.
  • message: The message of the operation. It will be a string.
  • data: The data of the operation. It will be a list of tuples.
  • formatted_data: The formatted data of the operation. It will be a list of dictionaries.

Add data

adding_list = [{"column_name": "value"}]
add_res = DH.add_data(table="table_name", adding_list=adding_list)

Get data

conditions = [("column_name =", "value")]
get_res = DH.get_data(table="table_name", conditional_rule_list=conditions)

Update data

update_list = [{"_id": 1, "column_name": "value1"},
               {"_id": 2, "column_name": "value2"}]
update_res = DH.update_data(table="table_name",editing_list=update_list, reference_column_list=["_id"])

Delete data

delete_list = [{"_id": 1},
               {"_id": 2}]
delete_res = DH.delete_data(table="table_name", filter_list=delete_list, reference_column_list=["_id"])

PostgresModelHandler & PostgresField

Define a schema model

User can create a model by inheriting the PostgresModelHandler class and defining the fields by PostgresField class.

from feliz_db.postgres_tools import PostgresModelHandler

class TestSchema(PostgresModelHandler):
    meta = {"initialize": True,
            "conditional_init": False,
            "init_type": "schema",
            "schema_name": ["test"],
            "authorization": "user"
    }

Create a schema

configs = {
    "host": "localhost",
    "port": 5432,
    "database": "postgres",
    "username": "postgres",
    "password": "postgres"
}

DH = PostgresHandler(**configs)

TestSchema.execute_sql(DH, TestSchema.form_schema_sql)

Define a table model

User can create a model by inheriting the PostgresModelHandler class and defining the fields by PostgresField class.

from feliz_db.postgres_tools import PostgresModelHandler, PostgresField

class UserListTable(PostgresModelHandler):
    _id           = PostgresField(serial=True, primary_key=True)
    modified_time = PostgresField("TIMESTAMP")
    user_id       = PostgresField("VARCHAR(20)", unique=True)
    full_name     = PostgresField("TEXT")
    password      = PostgresField("TEXT", default="''")
    comments      = PostgresField("TEXT", default="''")

    meta = {"initialize": True,
            "conditional_init": True,
            "init_type": "table",
            "schema_name": ["test"],
            "table_name": ["user_list"]}

    @classmethod
    def if_initialize(cls, schema_name, table_name):
        now = data_time.datetime.now()
        sql = f"""
        INSERT INTO {schema_name}.{table_name} (modified_time, user_id, full_name, password, comments)
            VALUES ( '{now}', 'admin', 'Administrator', '$2b$12$pDY0sUa6X4AB0kWySLY8lO2ioQtarEWoSeE0kUvg1bZEXMPXefcv.', '');
        """
        return sql

    @classmethod
    def else_initialize(cls, schema_name, table_name):
        return ""

Create a table

configs = {
    "host": "localhost",
    "port": 5432,
    "database": "postgres",
    "username: "postgres",
    "password": "postgres"
}

DH = PostgresHandler(**configs)

UserListTable.execute_sql(DH, UserListTable.form_table_conditional_sql)

Multiple create schema and table

All models should execute the create_sql method and then use any model to execute the execute_sql method to create the schema and table.

After creating the schema and table, the user can execute the clear_sql method to clear the schema and table.

Note: execute_sql and clear_sql can be executed by any model. Only the create_sql method should be executed by all models.

configs = {
    "host": "localhost",
    "port": 5432,
    "database": "postgres",
    "username": "postgres",
    "password": "postgres"
}
DH = PostgresHandler(**configs)

TestSchema.create_sql()
UserListTable.create_sql()
UserListTable.execute_sql(DH)
UserListTable.clear_sql()

Mongo Tools

DocumentHandler

DocumentHandler is a class that can be used to define a schema and table for a MongoDB database. The user can create a model by inheriting the DocumentHandler class and defining the fields by the mongoengine class.

from mongoengine import *
from feliz_db.mongo_tools import DocumentHandler

class ConfigCameras(DocumentHandler):
    item_id       = StringField(required=True, unique=True)
    item_name     = StringField(required=True)
    modified_time = DateTimeField(required=True)

    class Coordinates(EmbeddedDocument):
        dashboard = ListField(FloatField(), required=True)
    coordinates   = EmbeddedDocumentField(Coordinates)

    class Rtsp(EmbeddedDocument):
        username  = StringField(required=True)
        password  = StringField(required=True)
        params    = StringField(required=True)
        rtsp_url  = StringField(required=True)
    rtsp          = EmbeddedDocumentField(Rtsp)

    class Projection(EmbeddedDocument):
        source    = ListField(ListField(FloatField()))
        target    = ListField(ListField(FloatField()))
    projection    = EmbeddedDocumentField(Projection)

    comments      = DictField()

    meta = {"db_alias": "dt_config", "collection": "cameras"}

MongoHandler

Initialization

from feliz_db.mongo_tools import MongoHandler

configs = {
    "host": "localhost",
    "port": 5445,
    "database": "mongo",
    "username": "mongo",
    "password": "mongo",
    "schemas": {"cameras": ConfigCameras}
}

DH = MongoHandler(**configs)

MongoHandler will automatically create the model and then users can use the add_data, get_data, update_data, and delete_data methods to add, update, and delete data from a collection.

All methods will return a dictionary with the following keys:

  • indicator: The indicator of the operation. It will be True if the operation is successful, otherwise it will be False.
  • message: The message of the operation. It will be a string.
  • formatted_data: The formatted data of the operation. It will be a list of dictionaries.

Add data

add_res = DH.add_data("cameras", [{...}, {...}])

Get data

get_res = DH.get_data("cameras", {"rtsp.username": "admin"})

Update data

update_res = MH.update_data("cameras", {"item_id": "123"}, {"item_name": "ABC"})

Delete data

delete_res = MH.delete_data("cameras", {"item_id": "123"})

MongoWidget

MongoWidget is a class that can be used to query data from a MongoDB database. The user can use the get_data method to query data from a collection.

MongoWidget also provides the add_data, update_data, and delete_data methods to add, update, and delete data from a collection. However, these methods are not recommended for use because they are not safe. It is recommended to use the class MongoModelHandler to define a schema and table to add, update, and delete data.

from feliz_db.mongo_tools import MongoWidget

configs = {
    "host": "localhost",
    "port": 5445,
    "database": "mongo",
    "username": "mongo",
    "password": "mongo",
}
MW = MongoWidget(**configs)

get_res = MW.get_data("cameras", {"rtsp.username": "admin"})

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

feliz_db-0.1.0.tar.gz (20.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

feliz_db-0.1.0-py3-none-any.whl (19.3 kB view details)

Uploaded Python 3

File details

Details for the file feliz_db-0.1.0.tar.gz.

File metadata

  • Download URL: feliz_db-0.1.0.tar.gz
  • Upload date:
  • Size: 20.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.9

File hashes

Hashes for feliz_db-0.1.0.tar.gz
Algorithm Hash digest
SHA256 26cbfbd0f48800717af4c6547d4bbbf5907b6c7cd40a7b74c25feacb1bed5ac2
MD5 19f846dbc1cbdd34b17f23fad045809c
BLAKE2b-256 5eb3fb29aa0c1d76bf6421ae9f245a1a360a4bf9f97b5b6d9890bb0324a83106

See more details on using hashes here.

File details

Details for the file feliz_db-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: feliz_db-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 19.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.9

File hashes

Hashes for feliz_db-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 fba24fc4a1d07d7f60ea8e09bb9d8ff225e1e4ee205ba22c5124aca80bc02e6a
MD5 c7c1b3bd2d30bee50777f45ba51daed1
BLAKE2b-256 856f4103bf8f7fe6591cd97035a46d91a432a7e57a98c4408a5a63fc446ea60c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page