Metadata-Version: 2.4
Name: muffin-databases
Version: 0.7.0
Summary: Async support for a range of databases for Muffin framework
Keywords: sql,postgres,mysql,sqlite,asyncio,asgi,web,muffin
Author: Kirill Klenov
Author-email: Kirill Klenov <horneds@gmail.com>
License-Expression: MIT
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Framework :: AsyncIO
Requires-Dist: databases
Requires-Dist: muffin
Requires-Dist: aiomysql ; extra == 'mysql'
Requires-Dist: asyncpg ; extra == 'postgres'
Requires-Dist: aiosqlite ; extra == 'sqlite'
Requires-Python: >=3.11, <4
Project-URL: Homepage, https://github.com/klen/muffin-databases
Project-URL: Repository, https://github.com/klen/muffin-databases
Provides-Extra: mysql
Provides-Extra: postgres
Provides-Extra: sqlite
Description-Content-Type: text/x-rst

Muffin-Databases
################

.. _description:

**Muffin-Databases** -- Async support for a range of databases for Muffin_ Framework

.. _badges:

.. image:: https://github.com/klen/muffin-databases/workflows/tests/badge.svg
    :target: https://github.com/klen/muffin-databases/actions
    :alt: Tests Status

.. image:: https://img.shields.io/pypi/v/muffin-databases
    :target: https://pypi.org/project/muffin-databases/
    :alt: PYPI Version

.. image:: https://img.shields.io/pypi/pyversions/muffin-databases
    :target: https://pypi.org/project/muffin-databases/
    :alt: Python Versions

.. _contents:

.. contents::

.. _requirements:

Requirements
=============

- python >= 3.11

.. note:: The plugin supports only asyncio event loop (not trio)

.. _installation:

Installation
=============

**Muffin-Databases** should be installed using pip: ::

    $ pip install muffin-databases

Optionally you can install the required database drivers with: ::

    $ pip install muffin-databases[sqlite]
    $ pip install muffin-databases[postgres]
    $ pip install muffin-databases[mysql]

Driver support is provided using one of asyncpg_, aiomysql_, or aiosqlite_.

.. _usage:

Usage
=====

Setup the plugin and connect it into your app:

.. code-block:: python

    from muffin import Application
    from muffin_databases import Plugin as DB

    # Create Muffin Application
    app = Application('example')

    # Initialize the plugin
    # As alternative: db = DB(app, **options)
    db = DB(url='sqlite:///db.sqlite')
    db.setup(app)


That's it now you are able to use the plugin inside your views:

.. code-block:: python

    @app.route('/items', methods=['GET'])
    async def get_items(request):
        """Return a JSON with items from database."""
        rows = await db.fetch_all('SELECT * from items')
        return [dict(row) for row in rows]

    @app.route('/items', methods=['POST'])
    async def insert_item(request):
        """Store an item into database."""
        data = await request.data()  # parse formdata/json from the request
        await db.execute_many('INSERT INTO items (name, value) VALUES (:name, :value)', values=data)
        return 'OK'

The Muffin-Databases plugin is based on databases_. See the databases_'s docs for further references.


Public API
----------

**db.database** -- the underlying ``databases.Database`` instance. Raises ``RuntimeError`` if the
plugin is not initialized.

Any unknown attribute is proxied to ``db.database``, so the whole databases_ API is available
directly on the plugin: ``await db.fetch_all(...)``, ``await db.fetch_one(...)``,
``db.transaction()``, ``await db.execute_many(...)`` and so on.

The plugin manages the connection for you: on application startup it calls ``database.connect()``,
on shutdown it calls ``database.disconnect()``.


Options
-------

=========================== ======================================= ===========================
Name                        Default value                           Description
--------------------------- --------------------------------------- ---------------------------
**url**                     ``"sqlite:///:memory:"``                A database connection URL
**params**                  ``{}``                                  A database connection params
=========================== ======================================= ===========================

Unknown options are ignored.


You are able to provide the options when you are initiliazing the plugin:

.. code-block:: python

    db.setup(app, url='postgresql://localhost/example', params={'ssl': True, 'min_size': 5, 'max_size': 20})

Or setup it from ``Muffin.Application`` configuration using the ``DATABASES_`` prefix:

.. code-block:: python

   DATABASES_URL = 'postgresql://localhost/example'

``Muffin.Application`` configuration options are case insensitive

Environment variables use the ``{APP_NAME}_DATABASES_`` prefix (the default application name is
``muffin``): ::

    $ export MUFFIN_DATABASES_URL='postgresql://localhost/example'

.. _bugtracker:

Bug tracker
===========

If you have any suggestions, bug reports or
annoyances please report them to the issue tracker
at https://github.com/klen/muffin-databases/issues

.. _contributing:

Contributing
============

Development of Muffin-Databases happens at: https://github.com/klen/muffin-databases


Contributors
=============

* klen_ (Kirill Klenov)

.. _license:

License
========

Licensed under a `MIT license`_.

.. _links:


.. _klen: https://github.com/klen
.. _Muffin: https://github.com/klen/muffin

.. _asyncpg: https://github.com/MagicStack/asyncpg
.. _aiomysql: https://aiomysql.readthedocs.io/en/latest/
.. _aiosqlite: https://github.com/omnilib/aiosqlite
.. _databases: https://www.encode.io/databases/

.. _MIT license: http://opensource.org/licenses/MIT
