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
Provenance
- Commit
94cf620- Tree
1104831- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
1309038
1 file changed+92 added−2 removed
modified:docs/patterns/sqlalchemy.rst+92 added-2 removed
90 unmodified lines91 92 Manual Object Relational Mapping93 --------------------------------94 95-*coming soon*95+Manual object relational mapping has a few upsides and a few downsides96+versus the declarative approach from above. The main difference is that97+you define tables and classes separately and map them together. It's more98+flexible but a little more to type. In general it works similar to the99+declarative approach, so make sure to also split up your application into100+multiple modules in a package.101 102+Here the example `database.py` module for your application::103+104+ from sqlalchemy import create_engine, MetaData105+ from sqlalchemy.orm import scoped_session, sessionmaker106+107+ 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)114+115+As for the declarative approach you need to close down the session after116+each request. Put this into your application module::117+118+ from yourapplication.database import db_session119+120+ @app.after_request121+ def shutdown_session(response):122+ db_session.remove()123+ return response124+125+Here an example table and model (put that into `models.py` for instance)::126+127+ from sqlalchemy import Table, Column, Integer, String128+ from sqlalchemy.orm import mapper129+ from yourapplication.database import metadata, db_session130+131+ class User(object):132+ query = db_session.query_property()133+134+ def __init__(self, name=None, email=None):135+ self.name = name136+ self.email = email137+138+ def __repr__(self):139+ return '<User %r>' % (self.name, self.email)140+141+ 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)147+148+Querying and inserting works exactly the same as in the example above.149+150+151 SQL Abstraction Layer152 ---------------------153 100-*coming soon*154+If you just want to use the database system (and SQL) abstraction layer155+you basically only need the engine::156+157+ from sqlalchemy import create_engine, MetaData158+159+ engine = create_engine('sqlite:////tmp/test.db')160+ metadata = MetaData(bind=engine)161+162+Then you can either declare the tables in your code like in the examples163+above, or automatically load them::164+165+ users = Table('users', metadata, autoload=True)166+167+To insert data you can use the `insert` method. We have to get a168+connection first so that we can use a transaction:169+170+>>> con = engine.connect()171+>>> con.execute(users.insert(name='admin', email='admin@localhost'))172+173+SQLAlchemy will automatically commit for us.174+175+To query your database, yu use the engine directly or use a connection:176+177+>>> users.select(users.c.id == 1).execute().first()178+(1, u'admin', u'admin@localhost')179+180+These results are also dict-like tuples:181+182+>>> r = users.select(users.c.id == 1).execute().first()183+>>> r['name']184+u'admin'185+186+You can also pass string of SQL statements to the187+:meth:`~sqlalchemy.engine.base.Connection.execute` method:188+189+>>> engine.execute('select * from users where id = :1', [1]).first()190+(1, u'admin', u'admin@localhost')