-
Notifications
You must be signed in to change notification settings - Fork 0
Using the Database Session
The nlplib provides the session object as a mechanism to store and retrieve data from a relational database. All interactions with a database adding, querying, updating, and deleting are done within the context of a session.
The nlplib session object is based off of SQLAlchemy's session object. When using the SQLAlchemy storage back-end, the nlplib session is nothing more than a thin wrapper around an SQLAlchemy session.
Here we see two word objects being added to the database, using the session's add
method. Then we see the objects being queried using the session's access
attribute. Python's with
statement is used to provide a scope for manipulating a session instance. All interactions with a session should be done within the scope of the corresponding with
block.
import nlplib
db = nlplib.Database() # By default this uses an SQLite in-memory database.
with db as session :
session.add(nlplib.Word('foo'))
session.add(nlplib.Word('bar'))
with db as session :
print(list(session.access.vocabulary())) # Will print foo and bar.
Alternatively, the database instance can be used as a decorator, supplying a session object as the first argument to the function. This behaves identically to the second with
block above.
@db
def print_vocabulary (session) :
print(list(session.access.vocabulary())) # Will print foo and bar again.
print_vocabulary()
Use of the session is conceptually similar to a transaction. If an exception is raised before the with
block terminates, all changes to the database made within that block are rolled back.
try :
with db as session :
session.add(nlplib.Word('baz'))
session.add(nlplib.Word('qux'))
raise ArithmeticError # An arbitrary exception, new additions are rolled back.
except ArithmeticError :
pass
with db as session :
print(list(session.access.vocabulary())) # Will print foo and bar, but not baz or qux.
The full source text for this demo can be found here.