YFCEMBEDD 2019-09-07
sqlalchemy 最大的好处在于结构清晰化,以及迁移数据库不会造成过多的冗余。但是缺点是没有纯粹的的sql功能多,也没有纯粹的sql来的方便。但对于开发人员来讲,sqlalchmey最大的好处在于阅读代码更加直观。
本文主要我多年来使用sqlalchemy遇到的一些坑,以及应该如何去做,以及刚开始萌新容易遇到的错误,希望我这篇文章能够给予我个人的一些积累。
以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()