sqlalchemy 最大的好處在於結構清晰化,以及遷移數據庫不會形成過多的冗餘。可是缺點是沒有純粹的的sql功能多,也沒有純粹的sql來的方便。但對於開發人員來說,sqlalchmey最大的好處在於閱讀代碼更加直觀。mysql
本文主要我多年來使用sqlalchemy遇到的一些坑,以及應該如何去作,以及剛開始萌新容易遇到的錯誤,但願我這篇文章可以給予我我的的一些積累。sql
以MYSQL
爲例,注意password
中不要包含@
數據庫
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) db_url = 'mysql+pymysql://username:password@localhost:port/datebase' app.config['SQLALCHEMY_DATABASE_URI'] = db_url app.config["SQLALCHEMY_COMMIT_ON_TEARDOWN"] = True # 自動提交 app.config['SQLALCHEMY_ECHO'] = False # 若是True在打印出sql日誌 db = SQLAlchemy(app)
class BaseRoom(db.Model): __abstract__ = True # 生命跳過該class表的生成 id = db.Column(db.String(50), primary_key=True, comment='用戶的id') third_id = db.Column(db.String(50), nullable=False, comment='網站的id') title = db.Column(db.String(500), nullable=False, comment='題目') price = db.Column(db.Float(asdecimal=True), nullable=False, comment='價格') class DaxiangRoom(BaseRoom): __tablename__ = 'daxiang_daxiangroom' # 表名字 __table_args__ = {"useexisting": True} landlord_id = db.Column(db.ForeignKey('daxiang_daxianglandlord.id'), index=True) landlord = db.relationship('DaxiangLandlord', primaryjoin='DaxiangRoom.landlord_id == DaxiangLandlord.id', backref='daxiang_daxiangrooms')
class CtripRoomSqlAlchemyPipeline(object): # 將每行更新或寫入數據庫中 def process_item(self, item, spider): model = CtripRoom(hotel_id=item['hotel_id'], hotel_name=item['hotel_name'], city=item['city'], location=item['location'], type=item['type'], score=item['score'] ) try: db.session.add(model) db.session.commit() except Exception as e: # print(e) db.session.rollback() pass return item class lukeRoomUpdateSqlAlchemyPipeline(object): # 更新sql def process_item(self, item, spider): landlord_id = item['landlord_id'] model = LukeRoom.query.filter_by(id=item['house_id']).first() model.landlord_id = landlord_id model.is_finished = 1 db.session.add(model) db.session.commit()
from dbs.database import db from sqlalchemy.dialects.mysql import insert token = content['token'] city = content['city'] account = content['account'] platform = 'airbnb' user_id = content['user_id'] _id = platform + '_' + content['user_id'] _time = datetime.now(timezone('Asia/Shanghai')).strftime("%Y-%m-%d %H:%M:%S") # 插入的數據 comment_model = insert(User).values( id=_id, platform=platform, city=city, token=token, user_id=user_id, create_time=_time, account=account ) # 出現衝突後須要更新的數據 do_update_comment_model = comment_model.on_duplicate_key_update( id=_id, platform=platform, city=city, token=token, user_id=user_id, create_time=_time, account=account, user_status='' ) db.session.execute(do_update_comment_model) db.session.commit()