zaz/doc/build/_sources/main/examples_base.rst.txt

101 lines
2.5 KiB
ReStructuredText

For Base
--------
You need install ``peewee``
``pip install -U peewee``
Create table
^^^^^^^^^^^^
.. code-block:: python
import easymacro as app
from peewee import *
database_proxy = DatabaseProxy()
class BaseModel(Model):
class Meta:
database = database_proxy
legacy_table_names = False
class Contacts(BaseModel):
id = IdentityField()
name = CharField()
born = app.BaseDateField(null=True)
def create_table():
path = '/home/mau/test.odb'
if app.paths.exists(path):
db = app.docs.connect(path)
else:
db = app.docs.new('base', {'path': path})
tables = [Contacts]
db.initialize(database_proxy, tables)
return
Insert data
^^^^^^^^^^^
.. code-block:: python
def base_insert_data():
path = '/home/mau/test.odb'
db = app.docs.connect(path)
db.initialize(database_proxy)
rows = (
dict(name = 'Ingrid Bergman', born=app.dates.date(2001, 1, 1)),
dict(name = 'Sofia Loren', born=app.dates.date(2002, 2, 2)),
dict(name = 'Kim Novak', born=app.dates.date(2003, 3, 3)),
dict(name = 'Jane Fonda', born=app.dates.date(2004, 4, 4)),
dict(name = 'Marion Cotillar', born=app.dates.date(2005, 5, 5)),
)
for row in rows:
Contactos.insert(**row).execute()
return
Select data
^^^^^^^^^^^
.. code-block:: python
def base_select_data():
path = '/home/mau/test.odb'
db = app.docs.connect(path)
db.initialize(database_proxy)
query = Contactos.select()
rows = db.get_query(query).tuples
for row in rows:
print(row)
rows = db.get_query(query).dicts
for row in rows:
print(row)
return
You can get tuples or dict::
(1, 'Ingrid Bergman', datetime.date(2001, 1, 1))
(2, 'Sofia Loren', datetime.date(2002, 2, 2))
(3, 'Kim Novak', datetime.date(2003, 3, 3))
(4, 'Jane Fonda', datetime.date(2004, 4, 4))
(5, 'Marion Cotillar', datetime.date(2005, 5, 5))
{'id': 1, 'name': 'Ingrid Bergman', 'born': datetime.date(2001, 1, 1)}
{'id': 2, 'name': 'Sofia Loren', 'born': datetime.date(2002, 2, 2)}
{'id': 3, 'name': 'Kim Novak', 'born': datetime.date(2003, 3, 3)}
{'id': 4, 'name': 'Jane Fonda', 'born': datetime.date(2004, 4, 4)}
{'id': 5, 'name': 'Marion Cotillar', 'born': datetime.date(2005, 5, 5)}