What is the difference between S

2017-08-02  本文已影响0人  樊海鹏
    db_session = sessionmaker(bind=db.get_engine(db.get_app(), bind='bi_user_statistic'))
    db_session().query(xxxxx).filter()

Let's check the diferences:

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 is:

In the first way you are using a API developed for the Flask framework, called Flask-SQLAlchemy. It's the option if you are creating a Flask application, because the scope of the Session can be managed automatically by your application. You have many benefits like a infrastructure to establish a single Session, associated with the request, which is correctly constructed and torn down corresponding torn down at the end of a request.
In the second way is a pure SQLAlchemy app, so if you are using a library to connect a particular database, you can use just a SQLAlchemy API, for example, for a command-line script, background daemon, GUI interface-driven application, etc.
So, in a both way you can add, like:

Using a 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 just 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
Realize that I am connecting in the same database just for show that you can add using many ways.
上一篇 下一篇

猜你喜欢

热点阅读