Skip to content
Myr

Updated SQLAlchemy docs.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 1309038 · Browse files · 1 file+92 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+92 added−2 removed

  • other:+92 added−2 removed

1 file+92 added−2 removed

modified:docs/patterns/sqlalchemy.rst+92 added-2 removed
90 unmodified lines
9192Manual Object Relational Mapping93--------------------------------9495*coming soon*95Manual object relational mapping has a few upsides and a few downsides96versus the declarative approach from above. The main difference is that97you define tables and classes separately and map them together. It's more98flexible but a little more to type. In general it works similar to the99declarative approach, so make sure to also split up your application into100multiple modules in a package.101102Here the example `database.py` module for your application::103104 from sqlalchemy import create_engine, MetaData105 from sqlalchemy.orm import scoped_session, sessionmaker106107 engine = create_engine('sqlite:////tmp/test.db')108 metadata = MetaData()109 db_session = scoped_session(sessionmaker(autocommit=False,110 autoflush=False,111 bind=engine)) 112 def init_db():113 metadata.create_all(bind=engine)114115As for the declarative approach you need to close down the session after116each request. Put this into your application module::117118 from yourapplication.database import db_session119120 @app.after_request121 def shutdown_session(response):122 db_session.remove()123 return response124125Here an example table and model (put that into `models.py` for instance)::126127 from sqlalchemy import Table, Column, Integer, String128 from sqlalchemy.orm import mapper129 from yourapplication.database import metadata, db_session130131 class User(object):132 query = db_session.query_property()133134 def __init__(self, name=None, email=None):135 self.name = name136 self.email = email137138 def __repr__(self):139 return '<User %r>' % (self.name, self.email)140141 users = Table('users', metadata,142 Column('id', Integer, primary_key=True),143 Column('name', String(50), unique=True),144 Column('email', String(120), unique=True)145 )146 mapper(User, users)147148Querying and inserting works exactly the same as in the example above.149150151SQL Abstraction Layer152---------------------153100*coming soon*154If you just want to use the database system (and SQL) abstraction layer155you basically only need the engine::156157 from sqlalchemy import create_engine, MetaData158159 engine = create_engine('sqlite:////tmp/test.db')160 metadata = MetaData(bind=engine)161162Then you can either declare the tables in your code like in the examples163above, or automatically load them::164165 users = Table('users', metadata, autoload=True)166167To insert data you can use the `insert` method. We have to get a168connection first so that we can use a transaction:169170>>> con = engine.connect()171>>> con.execute(users.insert(name='admin', email='admin@localhost'))172173SQLAlchemy will automatically commit for us.174175To query your database, yu use the engine directly or use a connection:176177>>> users.select(users.c.id == 1).execute().first()178(1, u'admin', u'admin@localhost')179180These results are also dict-like tuples:181182>>> r = users.select(users.c.id == 1).execute().first()183>>> r['name']184u'admin'185186You can also pass string of SQL statements to the187:meth:`~sqlalchemy.engine.base.Connection.execute` method:188189>>> engine.execute('select * from users where id = :1', [1]).first()190(1, u'admin', u'admin@localhost')