Let me check the differences:
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://///Users/dedeco/Documents/tmp/testDb.db' db = SQLAlchemy(app) >>>type(db.session) <class 'sqlalchemy.orm.scoping.scoped_session'>
or
from sqlalchemy import * from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base some_engine = create_engine('sqlite://///Users/dedeco/Documents/tmp/testDb.db') Session = sessionmaker(bind=some_engine) session = Session() Base = declarative_base() >>> type(session) <class 'sqlalchemy.orm.session.Session'>
Basically the difference:
First of all, you use the API developed for the flash framework called Flask-SQLAlchemy. This is an option if you are creating a Flask application because the scope of the session can be controlled automatically by your application. You have many advantages, such as the infrastructure for creating a single session associated with the request, which is correctly constructed and torn down accordingly at the end of the request.
In the second case, it is just an SQLAlchemy application, so if you use the library to connect a specific database, you can only use the SQLAlchemy API, for example, for the command line script, background daemon, GUI, etc.
So, in both directions you can add, for example:
Using Flask-SQLAlchemy :
class User(db.Model): __tablename__ = 'users' user_id = db.Column(db.Integer(), primary_key = True) user_name = db.Column(db.String(80), unique=True) def __init__(self, user_name): self.user_name = user_name >>> db.create_all() >>> u = User('user1') >>> db.session.add(u) >>> db.session.commit() >>> users = db.session.query(User).all() >>> for u in users: ... print u.user_name ... user1
Using only SQLAlchemy :
class User(Base): __tablename__ = 'users' user_id = Column(Integer(), primary_key = True) user_name = Column(String(80), unique=True) >>> u = User() >>> u.user_name = 'user2' >>> session.add(u) >>> session.commit() >>> users = session.query(User).all() >>> for u in users: ... print u.user_name ... user1 user2
Understand that I am connecting in the same database only to show what you can add in different ways.
source share