streamlit-sqlalchemy


Namestreamlit-sqlalchemy JSON
Version 0.1.1 PyPI version JSON
download
home_page
SummarySome templating for streamlit and sqlalchemy
upload_time2024-02-23 16:42:02
maintainer
docs_urlNone
author
requires_python>=3.8
license
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": "",
    "name": "streamlit-sqlalchemy",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "database,sql,sqlalchemy,streamlit,templating",
    "author": "",
    "author_email": "artygo8 <arthurgossuin@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/50/ab/5b089b83ed479ec29bc3a97b40f34e7f7f381de5b6dbf62bcc953281b096/streamlit_sqlalchemy-0.1.1.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": "",
    "summary": "Some templating for streamlit and sqlalchemy",
    "version": "0.1.1",
    "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": "1a789ae91e28265cc77870defaefcbe071974177bbf20a91d726bb17fb21fe60",
                "md5": "84871c1b972a627132b9e7264cab4a91",
                "sha256": "a1884f1c1703d3365cff7c0326cb94086e8e5a7b0147d3b16ce7131e03272ab0"
            },
            "downloads": -1,
            "filename": "streamlit_sqlalchemy-0.1.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "84871c1b972a627132b9e7264cab4a91",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 12370,
            "upload_time": "2024-02-23T16:42:01",
            "upload_time_iso_8601": "2024-02-23T16:42:01.139015Z",
            "url": "https://files.pythonhosted.org/packages/1a/78/9ae91e28265cc77870defaefcbe071974177bbf20a91d726bb17fb21fe60/streamlit_sqlalchemy-0.1.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "50ab5b089b83ed479ec29bc3a97b40f34e7f7f381de5b6dbf62bcc953281b096",
                "md5": "f6f94016ac6db920c1e059152d89a3ff",
                "sha256": "057e11eff3fb4e5b4ce0dbd73b46b3aa179347e95b289ed57715b354fe6cb7f4"
            },
            "downloads": -1,
            "filename": "streamlit_sqlalchemy-0.1.1.tar.gz",
            "has_sig": false,
            "md5_digest": "f6f94016ac6db920c1e059152d89a3ff",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 9686329,
            "upload_time": "2024-02-23T16:42:02",
            "upload_time_iso_8601": "2024-02-23T16:42:02.786252Z",
            "url": "https://files.pythonhosted.org/packages/50/ab/5b089b83ed479ec29bc3a97b40f34e7f7f381de5b6dbf62bcc953281b096/streamlit_sqlalchemy-0.1.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-23 16:42:02",
    "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: 0.22418s