Skip to main content

Provide some methods for getting objects with SQLAlchemy

Project description

('Helpers SQLAlchemy - :class:`sqla_helpers.base_model.BaseModel`\n===============================================================\nInstallation\n-------------\n\n.. rubric:: Git\n\nInstallation from git\n\n.. code-block:: console\n\n $> git clone git@github.com:moumoutte/sqla_helpers.git\n $> cd sqla_helpers\n $> sudo python2.7 setup.py install\n\n.. rubric:: Eggs\n\nInstallation from pypi `eggs`\n\n.. code-block:: console\n\n $> sudo pip install sqla_helpers\n\n\nGetting Started\n----------------\n\nThe goal of :class:`sqla_helpers.base_model.BaseModel` is to provide syntactic sugar for :mod:`SQLAlchemy`.\n\n\n:class:`sqla_helpers.base_model.BaseModel` is to use as mixin class. This class inherits from nothing and shouldn\'t be inherited.\nFor access method from model, models need to be declared as bellow:\n\n.. code-block:: python\n\n from somewhere import DeclarativeBase\n from sqla_helpers.base_model import BaseModel\n\n class MyModel(DeclarativeBase, BaseModel):\n id = ... # Clef primaire , l\'identifiant sous forme d\'entier\n awesome_attr = ... # Attribut quelconque du mod\xc3\xa8le\n other_model = relationship(\'MyOtherModel\', backref=\'mymodel\')\n\n\n class MyOtherModel(DeclarativeBase, BaseModel):\n id = ... # Clef primaire\n name = ...\n model_id = ... # Clef \xc3\xa9trang\xc3\xa8re sur MyModel\n\n\nThe :class:`DeclarativeBase` class is generated by :func:`declarative_base` function from `SQLAlchemy`.\n\nTo avoid mixin uses, :class:`sqla_helpers.base_model.BaseModel` class can be used as `cls` parameter in :func:`declarative_base`\nfunction. \n\n.. code-block:: python\n\n from sqlalchemy.ext.declarative import declarative_base\n from sqla_helpers.base_model import BaseModel\n DeclarativeBase = declarative_base(cls=BaseModel)\n\n\n.. code-block:: python\n\n class MyModel(DeclarativeBase):\n # ...\n\n\n:class:`sqla_helpers.base_model.BaseModel` needs to build a session when queries are done.\nIn order to access a session when needing, the class uses the stored function :attr:`sqla_helpers.base_model.BaseModel.sessionmaker`. \nThis function will be called each time a session is needed.\nSo we need to store a session_maker by calling `sqla_helpers.base_model.BaseModel.register_sessionmaker` method.\n\n.. code-block:: python\n\n # Application\'s initialization\n def main():\n # ...\n BaseModel.register_sessionmaker(scoped_session(sessionmaker(bind=engine)))\n # ...\n\nFor a global session, you can just give a Session which is not a `callable`\n\n.. code-block:: python\n\n from somwhere import DBSession\n\n # Application\'s initialization\n def main():\n # ...\n BaseModel.register_sessionmaker(DBSession)\n # ...\n\nRegistering a session maker can be dangerous. Because, technically, we change dynamically a class method. To prevent errors, an exception , :exc:`sqla_helpers.base_model.SessionMakerExists`, is raised if a session maker is already registered.\n\nBut sometimes, perhaps you need to change it while application is running. So, you can force a new record even if a session maker is already registered\n\n.. code-block:: python\n\n >>> BaseModel.register_sessionmaker(db_session)\n >>> new_db_session = amazing_function()\n >>> BaseModel.register_sessionmaker(new_db_session)\n Traceback (most recent call last):\n File "<stdin>", line 1, in <module>\n SessionMakerExists: A session maker is already registered.\n >>> BaseModel.register_sessionmaker(new_db_session, force=True)\n \nBasic use case :\n\n.. code-block:: python\n\n >>> MyModel.all()\n [<MyModel object at 0x2c19d90>]\n >>> MyModel.get(id=2)\n <MyModel object at 0x2c19d90>\n >>> MyModel.get(id=3)\n *** NoResultFound: No row was found for one()\n >>> MyModel.filter(id=2)\n [<MyModel object at 0x2c19d90>]\n >>> MyModel.filter(id=3)\n []\n >>> MyModel.count(id=2)\n 1\n\n\n* :meth:`sqla_helpers.base_model.BaseModel.all` returns all the database objects\n* :meth:`sqla_helpers.base_model.BaseModel.filter` returns a list of matching objects.\n* :meth:`sqla_helpers.base_model.BaseModel.get` returns an uniq matching object.\n* :meth:`sqla_helpers.base_model.BaseModel.count` returns the number of matching objects.\n\nQuerying criterions can be chained with an `&&` (logical and) operator.\n\n.. code-block:: python\n\n >>> MyOtherModel.filter(name=\'toto\')\n [<MyOtherModel object at 0x2c19d90>, <MyOtherModel object at 0x2e27e08>]\n >>> MyOtherModel.filter(name=\'toto\', id=2)\n [<MyOtherModel object at 0x2c19d90>]\n\n\nQuerying for criterions on relations\n------------------------------------\n\nValid querying criterions for a class are defined by the class attributes.\nIE : in case of `MyOtherModel`, criterions can be `id`, `name` and `model_id`.\n\nThis is still true for a Sqlachemy relation.\n\nIE: querying all `MyModel` witch `MyOtherModel` have a name \'foo\'.\n\n.. code-block:: python\n\n >>> MyModel.filter(awesome_attr__name=\'foo\')\n [<MyModel object at 0x2c19d90>]\n\n\nQuerying with entire object.\n\n.. code-block:: python\n\n >>> otherModel = MyOtherModel.get(name=\'foo\')\n >>> MyModel.filter(awesome_attr=otherModel)\n [<MyModel object at 0x2c19d90>]\n\n\nThe `__` separator (double underscore) allows to split between the differents entities.\n\nQuering with relations attributes can be done recursively.\nIf `MyOtherObject` has an `other_attr` attribute which is in relation with a `MyOtherOtherObject` object.\n\nQuerying all `MyModel` with a `MyOtherObject` has `MyOtherOtherObject` has a `name` attribute is \'foo\'.\n\n.. code-block:: python\n\n >>> MyModel.filter(awesome_attr__other_attr__name=\'foo\')\n [<MyModel object at 0x2c19d90>]\n\n\n\nOperators\n---------\n\nOthers operators than equality can be used. Those operators should be written\nwith the attribute name following \'__\' (double underscore) and operator\'s name.\n\nIE: if all `MyModel` with `id` different than 2 are wanted:\n\n.. code-block:: python\n\n >>> MyModel.filter(id__not=2)\n []\n\nAvailable operators are:\n\n* \'not\': Non-equal,\n* \'lt\': letter than,\n* \'le\': letter or equals than,\n* \'gt\': gretter than,\n* \'ge\': gretter or equal than,\n* \'in\': in a list,\n* \'like\': SQL `LIKE` operator,\n* \'ilike\': SQL `ILIKE` operator.\n\n\nMore complex querying\n--------------------\n\nAs the Django way, :mod:`sqla_helpers` provides a :class:`sqla_helpers.logical.Q` object for more complex queries.\nThe :class:`sqla_helpers.logical.Q` object can use the :mod:`sqla_helpers\' syntax.\n\n.. code-block:: python\n\n >>> from sqla_helpers.logical import Q\n >>> Q(status__name=\'test\')\n <sqla_helpers.logical.Q at 0x2376cd0>\n\n\nThese objects are usable as criterions for query.\n\n:class:`sqla_helpers.base_model.BaseModel`\n\n.. code-block:: python\n\n >>> Treatment.get(Q(id=2))\n >>> <sqlalchemy_test.models.Treatment at 0x2388690>\n\nThe goal of those objects is to allow SQL logical conditions in a python syntax.\n\nIf all `Treatment` objects wih an `id` == 2 or a `Status` name == \'KO\' are wanted.\n\n.. code-block:: python\n\n >>> Treatment.filter(Q(id=2) | Q(status__name=\'KO\'))\n [<sqlalchemy_test.models.Treatment at 0x2388690>, <sqlalchemy_test.models.Treatment at 0x23837d0>]\n\n\nFor getting, all `Treatment` objects with an `id\' attribute different than 2 :\n\n.. code-block:: python\n\n >>> Treatment.filter(~Q(id=2))\n [<sqlalchemy_test.models.Treatment at 0x2383450>, <sqlalchemy_test.models.Treatment at 0x23837d0>,\n <sqlalchemy_test.models.Treatment at 0x23886d0> ]\n\nLogical operators can be chained :\n\n.. code-block:: python\n\n >>> Treatment.filter((Q(id=2) | Q(name=\'toto\')) & (Q(name=\'OK\') | ~Q(status__id=3)))\n 2013-02-10 16:39:49,485 INFO sqlalchemy.engine.base.Engine SELECT\n treatment.id AS treatment_id, treatment.name AS treatment_name,\n treatment.status_id AS treatment_status_id\n FROM treatment JOIN status ON status.id = treatment.status_id\n WHERE (treatment.id = ? OR treatment.name = ?) AND (treatment.name = ? OR\n status.id != ?)\n 2013-02-10 16:39:49,485 INFO sqlalchemy.engine.base.Engine (2, \'toto\', \'OK\',\n 3)\n >>> [<sqlalchemy_test.models.Treatment at 0x2388690>]\n\n\nJSON\n----\n\nOften in web oriented applications, client and server exchange with JSON format.\nIn order to have easier loading, :mod:`sqla_helpers` provides methods for loading from a regular python dictionary or a SQLAlchemy model object.\n\nThe :meth:`sqla_helpers.base_model.BaseModel.dump` method allows a JSON compatible dictionary.\n\n.. code-block:: python\n\n >>> print json.dumps(t.dump(), indent=4)\n {\n "status": {\n "id": 1,\n "name": "Ok"\n },\n "status_id": 1,\n "id": 1,\n "name": "Great Treatment"\n }\n\n\nThe method `sqla_helpers.base_model.BaseModel.load` can build objects from a dictionary.\nThe meaning of use a dictionary is to facilitate access to data in JSON or generate JSON from dictionary.\n\nObjects are getting from database if primary key attributes are found on the dictionnary. Otherwise new object\nare created.\n\n.. code-block:: python\n\n >>> t = Treatment.get(id=7)\n >>> t.name\n \'YEAH \\\\o/\'\n >>> t.id\n 7\n >>> t.status.name\n \'Holy status !\'\n >>> t.status.id\n 7\n >>> t = Treatment.load({\'id\': 7, \'name\': \'hello\'})\n >>> t.name, t.id\n (\'hello\', 7)\n >>> session.commit()\n >>> t.dump()\n {\n \'id\': 7,\n \'name\': u\'hello\',\n \'status\': {\'id\': 7, \'name\': u\'Holy status !\'},\n \'status_id\': 7\n }\n >>> tr = Treatment.load(t.dump())\n >>> tr == t\n True\n >>> tr.status == t.status\n True\n >>> Treatment.load(tr.dump()).dump()\n {\n \'id\': 7,\n \'name\': u\'hello\',\n \'status\': {\'id\': 7, \'name\': u\'Holy status !\'},\n \'status_id\': 7\n }\n >>> tr = Treatment.load({\'name\': \'new treatment\', \'status\': {\'name\': \'new status\'}})\n >>> tr.id\n None\n >>> tr.status.id\n None\n >>> session.add(tr)\n >>> session.commit()\n >>> tr.id\n 10\n >>> tr.status.id\n 8\n\n\n:class:`sqla_helpers.base_model.BaseModel` class\n================================================\n\n.. automodule:: sqla_helpers.base_model\n',)

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

sqla_helpers-0.5.1.tar.gz (15.1 kB view hashes)

Uploaded Source

Supported by

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