2

I have recently made a decision to start using the Pyramid (python web framework) for my projects from now on.

I have also decided to use SQLalchemy, and I want to use raw MySQL (personal reasons) but still keep the ORM features.

The first part of the code in models.py reads:

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()

Now from here how do I exectue a query for CREATE TABLE using raw MySQL.

the traditional SQLalchemy way would be:

class Page(Base):
 __tablename__ = 'pages'
 id = Column(Integer, primary_key=True)
 name = Column(Text, unique=True)
 data = Column(Text)
def __init__(self, name, data):
 self.name = name
 self.data = data
asked Feb 18, 2011 at 21:09

3 Answers 3

4
DBSession.execute('CREATE TABLE ....')

Have a look at sqlalchemy.text() for parametrized queries.

answered Feb 19, 2011 at 9:28
2
  • Thanks for your reply Marco. I have tried the following: DBSession.execute( """ CREATE TABLE ..... """ ) and recieve the following error: UnboundExecutionError: Could not locate a bind configured on SQL expression or this Session Commented Feb 19, 2011 at 9:48
  • yes, you have to call DBSession.configure(bind=get_engine(...)) or something like that, but I'm not into pyramid yet and don't know how it is set up. I usually create the schema in pure sql then call reflect() on the connection... Commented Feb 19, 2011 at 17:27
3

My own biased suggestion would be to use http://pypi.python.org/pypi/khufu_sqlalchemy to setup the sqlalchemy engine.

Then inside a pyramid view you can do something like:

from khufu_sqlalchemy import dbsession
db = dbsession(request)
db.execute("select * from table where id=:id", {'id':7})
answered Mar 6, 2011 at 17:26
0

Inside the views.py if you are adding form elements, first create an object of the database.

In your snippet, do it as

pg = Page() 

and add it with

DBSession.add(pg) 

for all the form elements you want to add e.g name and data from your snippet.

the final code would be similar to:

 pg = Page()
 name = request.params['name']
 data = request.params['data']
 DBSession.add(pg)
martin
3,2591 gold badge28 silver badges37 bronze badges
answered Aug 15, 2014 at 13:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.