Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

print out results to text box using sqlite3

12 views
Skip to first unread message

En Ware

unread,
Jan 23, 2017, 11:20:56 AM1/23/17
to Nagare users
Does anyone have any examples how to print out records from a sqlite3 database to the nagare app? 

apoirier

unread,
Jan 24, 2017, 10:58:59 AM1/24/17
to Nagare users
Hi,

To use a database with Nagare you need to activate the database in the
configuration file and define some SQLAlchemy entities in your code.


Here is an example of a persistent 'Counter'.

1. Install the database extension of Nagare

easy_install "nagare[database]"

2. Create the application structure

nagare-admin create-app counter
cd counter
python setup.py counter

3. Configure the database

In the 'conf/counter.cfg' file, set the 'activated' parameter of the '[database]' section to 'on'.

You can see by default the database is a SQLLite one:

[application]
path = app counter
name = counter
debug = off

[database]
activated = on
uri = sqlite:///$here/../data/counter.db
metadata = counter.models:__metadata__
debug = off

4. Defined your SQLAlchemy entities in the 'counter/models.py' file. Here a 'Counter':

from elixir import *
from sqlalchemy import MetaData
from nagare import presentation

__metadata__ = MetaData()

class Counter(Entity):
    name = Field(String)
    value = Field(Integer)

    def decrease(self):
        self.value -= 1

    def increase(self):
        self.value += 1

@presentation.render_for(Counter)
def render_counter(self, h, *args):
    h << h.div(self.value)
    with h.div:
        h << h.a('--').action(self.decrease)
        h << ' | '
        h << h.a('++').action(self.increase)

    return h.root

5. In the 'counter/app.py' file, code the application to create the counter with its initial value and to display it:

from nagare import presentation, component

from .models import Counter

class App(object):
    def __init__(self):
        counter = Counter.get_by(name='MyCounter') # Fetch the counter
        if counter is None:
            # Create the counter in database
            counter = Counter(name='MyCounter', value=0)
            counter.flush()

        self.counter = component.Component(counter)

@presentation.render_for(App)
def render_app(self, h, *args):
    h << h.h1('Counter in database')
    h << self.counter

    return h.root

app = App

6. Create the database structure. Nagare will discover your SQLAlchemy
entities and create the database tables:

nagare-admin create-db --drop --debug counter

7. Launch the application

nagare-admin serve --reload counter

8. Enjoy!
Reply all
Reply to author
Forward
0 new messages