| 1 |
.. _databases: |
| 2 |
|
| 3 |
Working with Databases, Transactions, and ORM's |
| 4 |
=============================================== |
| 5 |
|
| 6 |
Pecan provides no opinionated support for working with databases, but |
| 7 |
it's easy to hook into your ORM of choice. This article details best |
| 8 |
practices for integrating the popular Python ORM, SQLAlchemy_, into |
| 9 |
your Pecan project. |
| 10 |
|
| 11 |
.. _SQLAlchemy: http://sqlalchemy.org |
| 12 |
|
| 13 |
.. _init_model: |
| 14 |
|
| 15 |
``init_model`` and Preparing Your Model |
| 16 |
--------------------------------------- |
| 17 |
|
| 18 |
Pecan's default quickstart project includes an empty stub directory |
| 19 |
for implementing your model as you see fit. |
| 20 |
|
| 21 |
:: |
| 22 |
|
| 23 |
. |
| 24 |
└── test_project |
| 25 |
├── app.py |
| 26 |
├── __init__.py |
| 27 |
├── controllers |
| 28 |
├── model |
| 29 |
│ ├── __init__.py |
| 30 |
└── templates |
| 31 |
|
| 32 |
By default, this module contains a special method, :func:`init_model`. |
| 33 |
|
| 34 |
:: |
| 35 |
|
| 36 |
from pecan import conf |
| 37 |
|
| 38 |
def init_model(): |
| 39 |
""" |
| 40 |
This is a stub method which is called at application startup time. |
| 41 |
|
| 42 |
If you need to bind to a parsed database configuration, set up tables |
| 43 |
or ORM classes, or perform any database initialization, this is the |
| 44 |
recommended place to do it. |
| 45 |
|
| 46 |
For more information working with databases, and some common recipes, |
| 47 |
see https://pecan.readthedocs.io/en/latest/databases.html |
| 48 |
""" |
| 49 |
pass |
| 50 |
|
| 51 |
The purpose of this method is to determine bindings from your |
| 52 |
configuration file and create necessary engines, pools, |
| 53 |
etc. according to your ORM or database toolkit of choice. |
| 54 |
|
| 55 |
Additionally, your project's :py:mod:`model` module can be used to define |
| 56 |
functions for common binding operations, such as starting |
| 57 |
transactions, committing or rolling back work, and clearing a session. |
| 58 |
This is also the location in your project where object and relation |
| 59 |
definitions should be defined. Here's what a sample Pecan |
| 60 |
configuration file with database bindings might look like. |
| 61 |
|
| 62 |
:: |
| 63 |
|
| 64 |
# Server Specific Configurations |
| 65 |
server = { |
| 66 |
... |
| 67 |
} |
| 68 |
|
| 69 |
# Pecan Application Configurations |
| 70 |
app = { |
| 71 |
... |
| 72 |
} |
| 73 |
|
| 74 |
# Bindings and options to pass to SQLAlchemy's ``create_engine`` |
| 75 |
sqlalchemy = { |
| 76 |
'url' : 'mysql://root:@localhost/dbname?charset=utf8&use_unicode=0', |
| 77 |
'echo' : False, |
| 78 |
'echo_pool' : False, |
| 79 |
'pool_recycle' : 3600, |
| 80 |
'encoding' : 'utf-8' |
| 81 |
} |
| 82 |
|
| 83 |
And a basic model implementation that can be used to configure and |
| 84 |
bind using SQLAlchemy. |
| 85 |
|
| 86 |
:: |
| 87 |
|
| 88 |
from pecan import conf |
| 89 |
from sqlalchemy import create_engine, MetaData |
| 90 |
from sqlalchemy.orm import scoped_session, sessionmaker |
| 91 |
|
| 92 |
Session = scoped_session(sessionmaker()) |
| 93 |
metadata = MetaData() |
| 94 |
|
| 95 |
def _engine_from_config(configuration): |
| 96 |
configuration = dict(configuration) |
| 97 |
url = configuration.pop('url') |
| 98 |
return create_engine(url, **configuration) |
| 99 |
|
| 100 |
def init_model(): |
| 101 |
conf.sqlalchemy.engine = _engine_from_config(conf.sqlalchemy) |
| 102 |
|
| 103 |
def start(): |
| 104 |
Session.bind = conf.sqlalchemy.engine |
| 105 |
metadata.bind = Session.bind |
| 106 |
|
| 107 |
def commit(): |
| 108 |
Session.commit() |
| 109 |
|
| 110 |
def rollback(): |
| 111 |
Session.rollback() |
| 112 |
|
| 113 |
def clear(): |
| 114 |
Session.remove() |
| 115 |
|
| 116 |
Binding Within the Application |
| 117 |
------------------------------ |
| 118 |
|
| 119 |
There are several approaches to wrapping your application's requests |
| 120 |
with calls to appropriate model function calls. One approach is WSGI |
| 121 |
middleware. We also recommend Pecan :ref:`hooks`. Pecan comes with |
| 122 |
:class:`~pecan.hooks.TransactionHook`, a hook which can be used to wrap |
| 123 |
requests in database transactions for you. To use it, simply include it in |
| 124 |
your project's ``app.py`` file and pass it a set of functions related to |
| 125 |
database binding. |
| 126 |
|
| 127 |
:: |
| 128 |
|
| 129 |
from pecan import conf, make_app |
| 130 |
from pecan.hooks import TransactionHook |
| 131 |
from test_project import model |
| 132 |
|
| 133 |
app = make_app( |
| 134 |
conf.app.root, |
| 135 |
static_root = conf.app.static_root, |
| 136 |
template_path = conf.app.template_path, |
| 137 |
debug = conf.app.debug, |
| 138 |
hooks = [ |
| 139 |
TransactionHook( |
| 140 |
model.start, |
| 141 |
model.start_read_only, |
| 142 |
model.commit, |
| 143 |
model.rollback, |
| 144 |
model.clear |
| 145 |
) |
| 146 |
] |
| 147 |
) |
| 148 |
|
| 149 |
In the above example, on HTTP ``POST``, ``PUT``, and ``DELETE`` |
| 150 |
requests, :class:`~pecan.hooks.TransactionHook` takes care of the transaction |
| 151 |
automatically by following these rules: |
| 152 |
|
| 153 |
#. Before controller routing has been determined, :func:`model.start` |
| 154 |
is called. This function should bind to the appropriate |
| 155 |
SQLAlchemy engine and start a transaction. |
| 156 |
|
| 157 |
#. Controller code is run and returns. |
| 158 |
|
| 159 |
#. If your controller or template rendering fails and raises an |
| 160 |
exception, :func:`model.rollback` is called and the original |
| 161 |
exception is re-raised. This allows you to rollback your database |
| 162 |
transaction to avoid committing work when exceptions occur in your |
| 163 |
application code. |
| 164 |
|
| 165 |
#. If the controller returns successfully, :func:`model.commit` and |
| 166 |
:func:`model.clear` are called. |
| 167 |
|
| 168 |
On idempotent operations (like HTTP ``GET`` and ``HEAD`` requests), |
| 169 |
:class:`~pecan.hooks.TransactionHook` handles transactions following different |
| 170 |
rules. |
| 171 |
|
| 172 |
#. ``model.start_read_only()`` is called. This function should bind |
| 173 |
to your SQLAlchemy engine. |
| 174 |
|
| 175 |
#. Controller code is run and returns. |
| 176 |
|
| 177 |
#. If the controller returns successfully, ``model.clear()`` is |
| 178 |
called. |
| 179 |
|
| 180 |
Also note that there is a useful :func:`~pecan.decorators.after_commit` |
| 181 |
decorator provided in :ref:`pecan_decorators`. |
| 182 |
|
| 183 |
Splitting Reads and Writes |
| 184 |
-------------------------- |
| 185 |
|
| 186 |
Employing the strategy above with :class:`~pecan.hooks.TransactionHook` makes |
| 187 |
it very simple to split database reads and writes based upon HTTP methods |
| 188 |
(i.e., GET/HEAD requests are read-only and would potentially be routed |
| 189 |
to a read-only database slave, while POST/PUT/DELETE requests require |
| 190 |
writing, and would always bind to a master database with read/write |
| 191 |
privileges). It's also possible to extend |
| 192 |
:class:`~pecan.hooks.TransactionHook` or write your own hook implementation for |
| 193 |
more refined control over where and when database bindings are called. |
| 194 |
|
| 195 |
Assuming a master/standby setup, where the master accepts write requests and |
| 196 |
the standby can only get read requests, a Pecan configuration for sqlalchemy |
| 197 |
could be:: |
| 198 |
|
| 199 |
# Server Specific Configurations |
| 200 |
server = { |
| 201 |
... |
| 202 |
} |
| 203 |
|
| 204 |
# Pecan Application Configurations |
| 205 |
app = { |
| 206 |
... |
| 207 |
} |
| 208 |
|
| 209 |
# Master database |
| 210 |
sqlalchemy_w = { |
| 211 |
'url': 'postgresql+psycopg2://root:@master_host/dbname', |
| 212 |
'pool_recycle': 3600, |
| 213 |
'encoding': 'utf-8' |
| 214 |
} |
| 215 |
|
| 216 |
# Read Only database |
| 217 |
sqlalchemy_ro = { |
| 218 |
'url': 'postgresql+psycopg2://root:@standby_host/dbname', |
| 219 |
'pool_recycle': 3600, |
| 220 |
'encoding': 'utf-8' |
| 221 |
} |
| 222 |
|
| 223 |
|
| 224 |
Given the unique configuration settings for each database, the bindings would |
| 225 |
need to change from what Pecan's default quickstart provides (see |
| 226 |
:ref:`init_model` section) to accommodate for both write and read only |
| 227 |
requests:: |
| 228 |
|
| 229 |
|
| 230 |
from pecan import conf |
| 231 |
from sqlalchemy import create_engine, MetaData |
| 232 |
from sqlalchemy.orm import scoped_session, sessionmaker |
| 233 |
|
| 234 |
Session = scoped_session(sessionmaker()) |
| 235 |
metadata = MetaData() |
| 236 |
|
| 237 |
|
| 238 |
def init_model(): |
| 239 |
conf.sqlalchemy_w.engine = _engine_from_config(conf.sqlalchemy_w) |
| 240 |
conf.sqlalchemy_ro.engine = _engine_from_config(conf.sqlalchemy_ro) |
| 241 |
|
| 242 |
def _engine_from_config(configuration): |
| 243 |
configuration = dict(configuration) |
| 244 |
url = configuration.pop('url') |
| 245 |
return create_engine(url, **configuration) |
| 246 |
|
| 247 |
|
| 248 |
def start(): |
| 249 |
Session.bind = conf.sqlalchemy_w.engine |
| 250 |
metadata.bind = conf.sqlalchemy_w.engine |
| 251 |
|
| 252 |
|
| 253 |
def start_read_only(): |
| 254 |
Session.bind = conf.sqlalchemy_ro.engine |
| 255 |
metadata.bind = conf.sqlalchemy_ro.engine |
| 256 |
|
| 257 |
|
| 258 |
def commit(): |
| 259 |
Session.commit() |
| 260 |
|
| 261 |
|
| 262 |
def rollback(): |
| 263 |
Session.rollback() |
| 264 |
|
| 265 |
|
| 266 |
def clear(): |
| 267 |
Session.close() |
| 268 |
|
| 269 |
|
| 270 |
def flush(): |
| 271 |
Session.flush() |