streamlit-sqlalchemy


Namestreamlit-sqlalchemy JSON
Version 0.2.4 PyPI version JSON
download
home_pageNone
SummarySome templating for streamlit and sqlalchemy
upload_time2024-05-30 11:19:43
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseNone
keywords database sql sqlalchemy streamlit templating
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Streamlit SQLAlchemy Integration

## Overview

`streamlit_sqlalchemy` is a Python module that provides seamless integration between Streamlit and SQLAlchemy models. It simplifies the process of creating, updating, and deleting database objects through Streamlit's user-friendly interface.

![assets/crud_create.png](./assets/crud_create.png)
![assets/crud_update.png](./assets/crud_update.png)

## Features

- **Easy Initialization**: Initialize the SQLAlchemy connection with a simple method call.
- **CRUD Operations**: Create, read, update, and delete operations are streamlined with minimal code.
- **Dynamic Forms**: Automatically generate forms for creating and updating database objects.
- **SQLTypes Support**: `String`, `Text`, `Integer`, `Float`, `Boolean`, `Date`, `DateTime`, `Time`.
- **Foreign Key Support**: Easily handle foreign key relationships in forms.

## Installation

```bash
pip install streamlit_sqlalchemy
```

## Usage

1. **Initialize the Engine:**

    ```python
    from streamlit_sqlalchemy import StreamlitAlchemyMixin

    # Create your SQLAlchemy model
    class YourModel(Base, StreamlitAlchemyMixin):
        __tablename__ = "your_model"

        id = Column(Integer, primary_key=True)
        name = Column(String)
        active = Column(Boolean, default=True)
        count = Column(Integer)
        text = Column(Text)
        created_at = Column(DateTime)

    # Initialize the connection
        StreamlitAlchemyMixin.st_initialize(connection=conn)
    ```

2. **CRUD Tabs:**

    ```python
    YourModel.st_crud_tabs()
    ```

3. **Create Form:**

    ```python
    YourModel.st_create_form()
    ```

4. **Edit Button:**

    ```python
    your_model_instance.st_edit_button("Edit", {"field": "value"})
    ```

5. **Delete Button:**

    ```python
    your_model_instance.st_delete_button()
    ```

## Advanced Usage

1. **Customize behavior with Meta Attributes:**

    ```python
    class YourModel(Base, StreamlitAlchemyMixin):
        __tablename__ = "your_model"

        id = Column(Integer, primary_key=True)
        name = Column(String)
        active = Column(Boolean, default=True)
        count = Column(Integer)
        text = Column(Text)
        created_at = Column(DateTime)

        # Customize the form fields with non-defaults
        __st_input_meta__ = {
            'name': st.text_input,
            'active': lambda *a, **kw: st.checkbox(*a, **kw, value=False),
        }

        # Customize display of the instances in the selectbox
        __st_repr__ = lambda _self: f'{self.name} ({self.count})'

        # Customize the order of the instances in the selectbox
        __st_order_by__ = lambda _self: self.count
    ```

2. **CRUD Tabs:**

    ```python
    YourModel.st_crud_tabs(
        defaults={"name": "Default Name"},  # Will not appear in the create form
        filter_by={"active": True},  # Will filter the instances in the selectbox
        except_columns=["active"],  # Will not appear in the update form
        border=True,  # Will add a border around the form
    )
    ```

3. **Create Form:**

    ```python
    YourModel.st_create_form(
        defaults={"active": False},  # Will not appear in the form
        border=True,  # Will add a border around the form
    )
    ```

4. **Edit Button:**

    ```python
    your_model_instance.st_edit_button(
        "Edit",  # Button label
        {"name": "New Name"},  # Will be updated on click
        # Any other kwargs will be passed to the st.button
    )
    ```

5. **Delete Button:**

    ```python
    your_model_instance.st_delete_button(
        label="Delete",  # Button label
        # Any other kwargs will be passed to the st.button
    )
    ```

## Simple Example

```python
import streamlit as st
from sqlalchemy import create_engine, Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from streamlit_sqlalchemy import StreamlitAlchemyMixin

Base = declarative_base()

class ExampleModel(Base, StreamlitAlchemyMixin):
    __tablename__ = "example"

    id = Column(Integer, primary_key=True)
    name = Column(String)

# Initialize the connection
CONNECTION = st.connection("example_db", type="sql")
Base.metadata.create_all(CONNECTION.engine)
StreamlitAlchemyMixin.st_initialize(CONNECTION)

# Create CRUD tabs
ExampleModel.st_crud_tabs()
```

## Comprehensive Example

```python
import logging
from pathlib import Path

import streamlit as st

from examples.models import Base, Task, User
from streamlit_sqlalchemy import StreamlitAlchemyMixin


def show_single_task(task):
    col1, col2, col3 = st.columns([1, 1, 1])
    if task.done:
        col1.write(f" - ~~{task.description}~~")
        with col2:
            task.st_delete_button()
    else:
        if task.due_date:
            date_color = "red" if task.due_date < datetime.now() else "green"
            col1.write(f" - {task.description} (:{date_color}[{task.due_date.strftime('%H:%M - %d.%m.%Y')}])")
        else:
            col1.write(f" - {task.description}")
        with col2:
            task.st_edit_button("Done", {"done": True})
        with col3:
            task.st_delete_button()


def app():
    st.title("Streamlit SQLAlchemy Demo")

    User.st_crud_tabs()

    with CONNECTION.session as session:
        for user in session.query(User).all():
            with st.expander(f"### {user.name}'s tasks:"):
                c = st.container()

                st.write("**Add a new task:**")
                Task.st_create_form(defaults={"user_id": user.id, "done": False})
                with c:
                    if not user.tasks:
                        st.caption("No tasks yet.")

                    for task in user.tasks:
                        show_single_task(task)


def main():
    if not Path("example.db").exists():
        Base.metadata.create_all(CONNECTION.engine)

    StreamlitAlchemyMixin.st_initialize(connection=CONNECTION)

    app()


if __name__ == "__main__":
    # initialize the database connection
    # (see https://docs.streamlit.io/library/api-reference/connections/st.connection)
    CONNECTION = st.connection("example_db", type="sql")
    main()
```

You can explore this provided [example](./examples/example.py), and launch it from the root directory (because it relies on relative imports):

```bash
python -m streamlit run examples/example.py
```

![assets/streamlit-example-2023-12-31-16-12-91.gif](./assets/streamlit-example-2023-12-31-16-12-91.gif)


## Contributing

We welcome contributions! See our [contribution guidelines](./CONTRIBUTING) for more details.

## License

This project is licensed under the Apache License 2.0 - see the [LICENSE](./LICENSE) file for details.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "streamlit-sqlalchemy",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "database, sql, sqlalchemy, streamlit, templating",
    "author": null,
    "author_email": "artygo8 <arthurgossuin@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/09/b2/2b3c574fe216a9258fd814c93778b382f29646188906e9ef5c43d8c12a04/streamlit_sqlalchemy-0.2.4.tar.gz",
    "platform": null,
    "description": "# Streamlit SQLAlchemy Integration\n\n## Overview\n\n`streamlit_sqlalchemy` is a Python module that provides seamless integration between Streamlit and SQLAlchemy models. It simplifies the process of creating, updating, and deleting database objects through Streamlit's user-friendly interface.\n\n![assets/crud_create.png](./assets/crud_create.png)\n![assets/crud_update.png](./assets/crud_update.png)\n\n## Features\n\n- **Easy Initialization**: Initialize the SQLAlchemy connection with a simple method call.\n- **CRUD Operations**: Create, read, update, and delete operations are streamlined with minimal code.\n- **Dynamic Forms**: Automatically generate forms for creating and updating database objects.\n- **SQLTypes Support**: `String`, `Text`, `Integer`, `Float`, `Boolean`, `Date`, `DateTime`, `Time`.\n- **Foreign Key Support**: Easily handle foreign key relationships in forms.\n\n## Installation\n\n```bash\npip install streamlit_sqlalchemy\n```\n\n## Usage\n\n1. **Initialize the Engine:**\n\n    ```python\n    from streamlit_sqlalchemy import StreamlitAlchemyMixin\n\n    # Create your SQLAlchemy model\n    class YourModel(Base, StreamlitAlchemyMixin):\n        __tablename__ = \"your_model\"\n\n        id = Column(Integer, primary_key=True)\n        name = Column(String)\n        active = Column(Boolean, default=True)\n        count = Column(Integer)\n        text = Column(Text)\n        created_at = Column(DateTime)\n\n    # Initialize the connection\n        StreamlitAlchemyMixin.st_initialize(connection=conn)\n    ```\n\n2. **CRUD Tabs:**\n\n    ```python\n    YourModel.st_crud_tabs()\n    ```\n\n3. **Create Form:**\n\n    ```python\n    YourModel.st_create_form()\n    ```\n\n4. **Edit Button:**\n\n    ```python\n    your_model_instance.st_edit_button(\"Edit\", {\"field\": \"value\"})\n    ```\n\n5. **Delete Button:**\n\n    ```python\n    your_model_instance.st_delete_button()\n    ```\n\n## Advanced Usage\n\n1. **Customize behavior with Meta Attributes:**\n\n    ```python\n    class YourModel(Base, StreamlitAlchemyMixin):\n        __tablename__ = \"your_model\"\n\n        id = Column(Integer, primary_key=True)\n        name = Column(String)\n        active = Column(Boolean, default=True)\n        count = Column(Integer)\n        text = Column(Text)\n        created_at = Column(DateTime)\n\n        # Customize the form fields with non-defaults\n        __st_input_meta__ = {\n            'name': st.text_input,\n            'active': lambda *a, **kw: st.checkbox(*a, **kw, value=False),\n        }\n\n        # Customize display of the instances in the selectbox\n        __st_repr__ = lambda _self: f'{self.name} ({self.count})'\n\n        # Customize the order of the instances in the selectbox\n        __st_order_by__ = lambda _self: self.count\n    ```\n\n2. **CRUD Tabs:**\n\n    ```python\n    YourModel.st_crud_tabs(\n        defaults={\"name\": \"Default Name\"},  # Will not appear in the create form\n        filter_by={\"active\": True},  # Will filter the instances in the selectbox\n        except_columns=[\"active\"],  # Will not appear in the update form\n        border=True,  # Will add a border around the form\n    )\n    ```\n\n3. **Create Form:**\n\n    ```python\n    YourModel.st_create_form(\n        defaults={\"active\": False},  # Will not appear in the form\n        border=True,  # Will add a border around the form\n    )\n    ```\n\n4. **Edit Button:**\n\n    ```python\n    your_model_instance.st_edit_button(\n        \"Edit\",  # Button label\n        {\"name\": \"New Name\"},  # Will be updated on click\n        # Any other kwargs will be passed to the st.button\n    )\n    ```\n\n5. **Delete Button:**\n\n    ```python\n    your_model_instance.st_delete_button(\n        label=\"Delete\",  # Button label\n        # Any other kwargs will be passed to the st.button\n    )\n    ```\n\n## Simple Example\n\n```python\nimport streamlit as st\nfrom sqlalchemy import create_engine, Column, String, Integer\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom streamlit_sqlalchemy import StreamlitAlchemyMixin\n\nBase = declarative_base()\n\nclass ExampleModel(Base, StreamlitAlchemyMixin):\n    __tablename__ = \"example\"\n\n    id = Column(Integer, primary_key=True)\n    name = Column(String)\n\n# Initialize the connection\nCONNECTION = st.connection(\"example_db\", type=\"sql\")\nBase.metadata.create_all(CONNECTION.engine)\nStreamlitAlchemyMixin.st_initialize(CONNECTION)\n\n# Create CRUD tabs\nExampleModel.st_crud_tabs()\n```\n\n## Comprehensive Example\n\n```python\nimport logging\nfrom pathlib import Path\n\nimport streamlit as st\n\nfrom examples.models import Base, Task, User\nfrom streamlit_sqlalchemy import StreamlitAlchemyMixin\n\n\ndef show_single_task(task):\n    col1, col2, col3 = st.columns([1, 1, 1])\n    if task.done:\n        col1.write(f\" - ~~{task.description}~~\")\n        with col2:\n            task.st_delete_button()\n    else:\n        if task.due_date:\n            date_color = \"red\" if task.due_date < datetime.now() else \"green\"\n            col1.write(f\" - {task.description} (:{date_color}[{task.due_date.strftime('%H:%M - %d.%m.%Y')}])\")\n        else:\n            col1.write(f\" - {task.description}\")\n        with col2:\n            task.st_edit_button(\"Done\", {\"done\": True})\n        with col3:\n            task.st_delete_button()\n\n\ndef app():\n    st.title(\"Streamlit SQLAlchemy Demo\")\n\n    User.st_crud_tabs()\n\n    with CONNECTION.session as session:\n        for user in session.query(User).all():\n            with st.expander(f\"### {user.name}'s tasks:\"):\n                c = st.container()\n\n                st.write(\"**Add a new task:**\")\n                Task.st_create_form(defaults={\"user_id\": user.id, \"done\": False})\n                with c:\n                    if not user.tasks:\n                        st.caption(\"No tasks yet.\")\n\n                    for task in user.tasks:\n                        show_single_task(task)\n\n\ndef main():\n    if not Path(\"example.db\").exists():\n        Base.metadata.create_all(CONNECTION.engine)\n\n    StreamlitAlchemyMixin.st_initialize(connection=CONNECTION)\n\n    app()\n\n\nif __name__ == \"__main__\":\n    # initialize the database connection\n    # (see https://docs.streamlit.io/library/api-reference/connections/st.connection)\n    CONNECTION = st.connection(\"example_db\", type=\"sql\")\n    main()\n```\n\nYou can explore this provided [example](./examples/example.py), and launch it from the root directory (because it relies on relative imports):\n\n```bash\npython -m streamlit run examples/example.py\n```\n\n![assets/streamlit-example-2023-12-31-16-12-91.gif](./assets/streamlit-example-2023-12-31-16-12-91.gif)\n\n\n## Contributing\n\nWe welcome contributions! See our [contribution guidelines](./CONTRIBUTING) for more details.\n\n## License\n\nThis project is licensed under the Apache License 2.0 - see the [LICENSE](./LICENSE) file for details.\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Some templating for streamlit and sqlalchemy",
    "version": "0.2.4",
    "project_urls": {
        "Homepage": "https://github.com/artygo8/streamlit-sqlalchemy",
        "Issues": "https://github.com/artygo8/streamlit-sqlalchemy/issues"
    },
    "split_keywords": [
        "database",
        " sql",
        " sqlalchemy",
        " streamlit",
        " templating"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d0a32cfb241516da4c6d843568a7a004bdbd097bb085c6aebcb57d75d27e90c3",
                "md5": "de1af78876fc5ebe9c8a8a7f19fb4794",
                "sha256": "7ddf2ebce4c059e4797ba69c1e7baf9ee95639278d4fd9c195f947f1f28c604a"
            },
            "downloads": -1,
            "filename": "streamlit_sqlalchemy-0.2.4-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "de1af78876fc5ebe9c8a8a7f19fb4794",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 12451,
            "upload_time": "2024-05-30T11:19:42",
            "upload_time_iso_8601": "2024-05-30T11:19:42.214772Z",
            "url": "https://files.pythonhosted.org/packages/d0/a3/2cfb241516da4c6d843568a7a004bdbd097bb085c6aebcb57d75d27e90c3/streamlit_sqlalchemy-0.2.4-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "09b22b3c574fe216a9258fd814c93778b382f29646188906e9ef5c43d8c12a04",
                "md5": "95c45c9fcf774b7feaae1c0d9890e4d6",
                "sha256": "faa6afaa15eff29290a1866393085f2bc7e0e2f61b68bccf51824a6691275620"
            },
            "downloads": -1,
            "filename": "streamlit_sqlalchemy-0.2.4.tar.gz",
            "has_sig": false,
            "md5_digest": "95c45c9fcf774b7feaae1c0d9890e4d6",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 9686700,
            "upload_time": "2024-05-30T11:19:43",
            "upload_time_iso_8601": "2024-05-30T11:19:43.554432Z",
            "url": "https://files.pythonhosted.org/packages/09/b2/2b3c574fe216a9258fd814c93778b382f29646188906e9ef5c43d8c12a04/streamlit_sqlalchemy-0.2.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-05-30 11:19:43",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "artygo8",
    "github_project": "streamlit-sqlalchemy",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "streamlit-sqlalchemy"
}
        
Elapsed time: 4.50621s