I moved to elixir when declarative_base caused the exact same issue.
Elixir still uses sqlalchemy's session so am I at least using the
session correctly?
Here is declarative_base code
#!/usr/bin/env python
########################################################################
#
#
# MODEL
#
#
#
########################################################################
import sqlalchemy
from sqlalchemy import Table, Column, Integer, String, MetaData,
ForeignKey
from sqlalchemy.orm import relation, backref
from sqlalchemy.orm import mapper
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import mapper
# engine is the connection to the database
engine = create_engine('sqlite:///:memory:', echo=True) # TODO: Move
to a Conf file
Base = declarative_base(bind=engine)
class Test(Base):
""" ORM for Tests. """
__tablename__ = "tests"
id = Column(Integer, primary_key=True)
name = Column(String(50))
def __init__(self,name):
""" Accepts a name for a test """
#TODO: Ensure valid input
self.name = name
class Question(Base):
""" ORM for Questions. """
__tablename__ = "questions"
id = Column(Integer, primary_key=True)
test_id = Column(Integer, ForeignKey("tests.id"))
question = Column(String)
test = relation(Test, backref=backref('questions', order_by=id))
def __init__(self,test_id, question):
""" Accepts a test_id and a question to sign that test """
#TODO: Ensure valid input
self.question = question
self.test_id = test_id
class Answer(Base):
""" ORM for Answers. """
__tablename__ = "answers"
id = Column(Integer, primary_key=True)
question_id = Column(Integer, ForeignKey("questions.id"))
answer = Column(String)
correct = Column(String(1), default='n') # y for correct n for not
question = relation(Question, backref=backref('answers',
order_by=id))
def __init__(self,question_id,answer,correct=0):
""" Accepts a question_id and a answer to assign to that
question.
Optionally it accepts correct, y for correct, n for not
Default for correct is n"""
#TODO: Ensure vaild input
self.question_id = question_id
self.answer = answer
self.correct = correct
Base.metadata.create_all(engine) # Create all tables
# Session class is how we talk to the engine (database)
Session = sessionmaker(bind=engine)
########################################################################
#
#
# VIEW/CONTROLLER
#
# Will Seperate Later
#
#
#
########################################################################
import cherrypy
class WebTest(object):
""" Cherrypy server root """
def header(self):
""" Defines a header to be used for web pages... Should be
temporary """
return "<html><head><title>pyWebTest</title></head><body>"
def footer(self):
""" Defines a footer to be used for web pages... Should also
be temporary """
return "</body></html>"
@cherrypy.expose()
def index(self):
""" Root page for pyWebTest server """
session = Session()
test = Test("network+")
session.add(test)
print session.dirty
session.commit
print session.dirty
return self.header() + "<h1>Web Test</h1>" + self.footer()
def main():
cherrypy.quickstart(WebTest())
return 0
if __name__ == '__main__': main()
On Aug 4, 7:49 am, "Michael Bayer" <[email protected]> wrote:
> this appears to be an Elixir issue, check on their list.
>
> kportertx wrote:
>
> > for some reason I cannot get my session to commit within a class
>
> > Here is the error.
> > Traceback (most recent call last):
> > File "/usr/local/lib/python2.6/dist-packages/cherrypy/
> > _cprequest.py", line 606, in respond
> > cherrypy.response.body = self.handler()
> > File "/usr/local/lib/python2.6/dist-packages/cherrypy/
> > _cpdispatch.py", line 25, in __call__
> > return self.callable(*self.args, **self.kwargs)
> > File "WebTest.py", line 106, in index
> > session.flush()
> > File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/
> > scoping.py", line 123, in do
> > return getattr(self.registry(), name)(*args, **kwargs)
> > File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/
> > session.py", line 1354, in flush
> > self._flush(objects)
> > File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/
> > session.py", line 1432, in _flush
> > flush_context.execute()
> > File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/
> > unitofwork.py", line 257, in execute
> > UOWExecutor().execute(self, tasks)
> > File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/
> > unitofwork.py", line 720, in execute
> > self.execute_save_steps(trans, task)
> > File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/
> > unitofwork.py", line 735, in execute_save_steps
> > self.save_objects(trans, task)
> > File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/
> > unitofwork.py", line 726, in save_objects
> > task.mapper._save_obj(task.polymorphic_tosave_objects, trans)
> > File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/
> > mapper.py", line 1387, in _save_obj
> > c = connection.execute(statement.values(value_params), params)
> > File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/engine/
> > base.py", line 824, in execute
> > return Connection.executors[c](self, object, multiparams, params)
> > File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/engine/
> > base.py", line 874, in _execute_clauseelement
> > return self.__execute_context(context)
> > File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/engine/
> > base.py", line 896, in __execute_context
> > self._cursor_execute(context.cursor, context.statement,
> > context.parameters[0], context=context)
> > File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/engine/
> > base.py", line 950, in _cursor_execute
> > self._handle_dbapi_exception(e, statement, parameters, cursor,
> > context)
> > File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/engine/
> > base.py", line 931, in _handle_dbapi_exception
> > raise exc.DBAPIError.instance(statement, parameters, e,
> > connection_invalidated=is_disconnect)
> > OperationalError: (OperationalError) no such table: __main___test
> > u'INSERT INTO __main___test (name) VALUES (?)' ['network']
>
> > And here is the code
>
> > #!/usr/bin/env python
> > ########################################################################
> > #
> > #
> > # MODEL
> > #
> > #
> > #
> > ########################################################################
> > from elixir import *
>
> > global session, metadata
> > metadata.bind = 'sqlite:///:memory:'
> > metadata.echo = True
>
> > class Test(Entity):
> > """ ORM for Tests. """
> > id = Field(Integer, primary_key = True)
> > name = Field(Unicode(50), required = True)
> > questions = OneToMany('Question')
>
> > def __init__(self,name):
>
> > """ Accepts a name for a test """
> > #TODO: Ensure valid input
> > self.name = name
>
> > class Question(Entity):
> > """ ORM for Questions. """
> > id = Field(Integer, primary_key = True)
> > question = Field(UnicodeText, required = True)
> > test = ManyToOne('Test')
> > answers = OneToMany('Answer')
>
> > def __init__(self,test_id, question):
> > """ Accepts a test_id and a question to sign that test """
> > #TODO: Ensure valid input
>
> > self.question = question
>
> > class Answer(Entity):
> > """ ORM for Answers. """
> > id = Field(Integer, primary_key = True)
> > answer = Field(UnicodeText, required = True)
> > correct = Field(Unicode(1), required = True) # y for correct n for
> > not
> > question = ManyToOne('Question')
>
> > def __init__(self,question_id,answer,correct=0):
> > """ Accepts a question_id and a answer to assign to that
> > question.
> > Optionally it accepts correct, y for correct, n for not
> > Default for correct is n"""
> > #TODO: Ensure vaild input
>
> > self.answer = answer
> > self.correct = correct
>
> > setup_all()
> > create_all()
>
> > ########################################################################
> > #
> > #
> > # VIEW/CONTROLLER
> > #
> > # Will Seperate Later
> > #
> > #
> > #
> > ########################################################################
>
> > import cherrypy
>
> > class WebTest(object):
> > """ Cherrypy server root """
>
> > def header(self):
> > """ Defines a header to be used for web pages... Should be
> > temporary """
> > return '<html><head><title>pyWebTest</title></head><body>'
>
> > def footer(self):
> > """ Defines a footer to be used for web pages... Should also
> > be temporary """
> > return '</body></html>'
>
> > @cherrypy.expose()
> > def index(self):
> > """ Root page for pyWebTest server """
> > output = 'BEGIN<br />'
> > test = Test('network')
> > output = output + 'The test ' + test.name + ' has been
> > initialized!<br />'
> > test1 = Test('A+')
> > output = output + str(session.new)+ '<br />'
> > output = output + str(session.dirty) + '<br />'
> > session.flush()
> > session.commit()
> > if test.id >=0:
> > output = output + 'Test has been added<br />'
> > output = output + str(test1.id) + '<br />'
> > #session.query(Test).all()
> > #session.query(Test).filter(Test.name.in_(['network
> > +','fake'])).all()
> > output = output + 'DONE <br />'
> > return self.header() + output + self.footer()
>
> > def main():
> > cherrypy.quickstart(WebTest())
> > return 0
>
> > if __name__ == '__main__': main()
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---