[PonyORM-list] (no subject)
Stefan Dröge
stefan at sdroege.de
Thu Dec 13 08:34:26 UTC 2018
I already asked the question on stackoverflow, however I just found this
mailing list, so I thought I'd cross post my question here:
(Original question from Stackoverflow:
https://stackoverflow.com/questions/53748730/when-using-pony-orm-or-sqlalchemy-where-to-create-database-object
)
I began playing a bit with Object Relational Mappers (*Pony ORM*
specifically).
In *Pony*, all entity definitions inherit from the [`db.Entity`][1] class.
However in order to do that of course the `db` object needs to be created
first somewhere. (`db.Entity` is somewhat similar to the declarative base
in *sqlalchemy*, so I believe my question below is also similar valid for
*sqlalchemy*)
All the examples I have seen in the Pony ORM docs present the examples
inline, where the Database object `db` is simply declared in the
interpreter prompt before the entities are declared.
This leaves for me the question: **Where should I create my db object in a
"real" project?.**
Especially consider the case where I want to keep my entity definitions
separate from where I actually use these entities (say I only want to build
a nice ORM wrapper package to access a database, which then should be used
in multiple different other projects). Then I probably want the users to
provide the own `db` object that is configured to their needs in order to
access the DB.
## Some example code:
Say I have a Database that stores *persons* and *addresses* and my package
`my_orm` should provide an ORM for the database, which then will be used in
`app.py`:
*my_orm/__init__.py*
from my_orm.person import Person
from my_orm.address import Address
*my_orm/person.py:*
from pony.orm import Required
class Person(db.Entity): # Where should `db` be defined?
name = Required(str)
age = Required(int)
*my_orm/address.py:*
from pony.orm import Required
class Address(db.Entity): # Where should `db` be defined?. Must be the
same `db` object as in person.py
street_name = Required(str)
zip_code = Required(int)
*app.py*
from pony.orm import Database
db = Database()
import my_orm
Besides already looking ugly because it mixes the imports with the creation
of the db, this will also throw the error `NameError: name 'db' is not
defined`. So what should I do instead?
[1]: https://docs.ponyorm.com/api_reference.html#Database.Entity
-------------- next part --------------
An HTML attachment was scrubbed...
URL: </ponyorm-list/attachments/20181213/14110ded/attachment.html>
More information about the ponyorm-list
mailing list