SQLAlchemy本身實際上建議你使用Flask包裝器(db.Model)作爲Flask項目。這就是說,我已經在我的Flask項目中使用了declarative_base模型,它更有意義。
它從flask-sqlalchemy中擊敗了SQLAlchemy類的整個目的。
下面是一些示例代碼:
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
import datetime
#set up sqlalchemy
engine = create_engine('postgresql://<username>:<password>@localhost/flask_database')
Base = declarative_base()
metadata = Base.metadata
metadata.bind = engine
Session = sessionmaker(bind=engine, autoflush=True)
session = Session()
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
api_owner_id = Column(Integer, ForeignKey('api.id'))
email = Column(String(120), unique=True)
username = Column(String(120), unique=True)
first_name = Column(String(120))
last_name = Column(String(120))
business_name = Column(String(120))
account_type = Column(String(60))
mobile_phone = Column(String(120))
street = Column(String(120))
street2 = Column(String(120))
city = Column(String(120))
state = Column(String(120))
zip_code = Column(String(120))
country = Column(String(120))
creation_date = Column(DateTime, default=datetime.datetime.now())
password = Column(String(120))
#github stuffs
github_link = Column(Boolean, default=False)
github_usn = Column(String(120))
github_oauth_token = Column(String(160))
#balanced stuffs
balanced_account_uri = Column(String(120))
ach_verified = Column(Boolean, default=False)
active = Column(Boolean, default=True)
profile_updated = Column(Boolean, default=False)
account_balance = Column(Numeric(precision=10, scale=2), default=0.00)
admin = Column(Boolean, default=False)
devapp = relationship('DevApp', backref="user", lazy="dynamic")
projects = relationship('Project', backref="user", lazy="dynamic")
proposals = relationship('Proposal', backref="user", lazy="dynamic")
transactions = relationship('Monies', backref="user", lazy="dynamic")
def __repr__(self):
return self.email
您的會話/引擎位有助於說明您的答案。所以,在我的燒瓶應用程序中,我需要傳遞會話以供使用。每次使用後,我是否需要以任何方式清理會話? (也許使用** app.do_teardown_xxx **?) – user2097818
在sessionmaker中使用autoflush = True參數不需要清理。 user = User(email =「[email protected]」) session.add(user) session.commit() –
我不打算在多個線程中運行此操作,但我將使用離散模塊每個使用他們自己的新會話。我打算通過會議制定者。這些模塊將進行逐步更新。提交每個會話實例後,是否應該有任何理由擔心數據完整性? (假設我的承諾不會互相打破)。 – user2097818