sqlaclhemy 相关用法
sqlalchemy 相关用法
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')
进行一个session的提交,查找,更新
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()
使用sqlalchemy 实现ON DUPLICATE KEY UPDATE
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()
相关推荐
liuweiq 2020-06-14
emmm00 2020-06-14
lt云飞扬gt 2020-05-29
朱建伟 2020-05-14
猛禽的编程艺术 2020-05-06
苦咖啡flask 2020-05-04
dreamhua 2020-04-30
dreamhua 2020-04-30
tanrong 2020-04-30
xuanlvhaoshao 2020-04-26
tanrong 2020-04-18
Danialzhou 2020-04-11
happinessaflower 2020-03-01
xiaoxiangyu 2020-02-23
喝绿茶的猫 2020-01-18
疯狂老司机 2020-01-10
liuyang000 2020-01-08
Lingforme 2020-01-08