sqlachemy 初探

来源:互联网 发布:老九门百度云同步网络 编辑:程序博客网 时间:2024/05/20 05:27

    • sqlAchemy
      • 简介
      • 安装
      • 使用
        • 创建数据库表
        • 创建对应类
        • 初始化数据库配置相关
        • 使用
      • sessionmaker 探讨

sqlAchemy

简介

SQLAlchemy是Python编程语言下的一款开源软件。提供了SQL工具包及对象关系映射(ORM)工具,使用MIT许可证发行。

类似于Hibernate

安装

使用

  1. 创建数据库表 (此处使用MySql)
  2. 创建与数据库表对应的类
  3. 初始化数据库配置相关,并使用

创建数据库表

CREATE TABLE `test`.`new_table` (  `id` INT NOT NULL AUTO_INCREMENT,  `name` VARCHAR(45) NULL,  PRIMARY KEY (`id`));

创建对应类

from sqlalchemy import Column, String, create_engine, INTfrom sqlalchemy.orm import sessionmakerfrom sqlalchemy.ext.declarative import declarative_baseBase = declarative_base()  #获得一个基类,也可以自定义一个进行扩展 class User(Base):    __tablename__ = 'user'    id = Column(INT, primary_key=True)    name = Column(String(45))

初始化数据库配置相关

db_url = 'mysql+mysqlconnector://root:hpulfc@localhost:3306/test'  # 连接地址engine = create_engine(db_url)  # 创建一个引擎DBsession = sessionmaker(bind=engine)  # 得到一个sessionmaker对象 ,后面细讲session = DBsession()  # 获得一个session初始化完成

使用

session.add(user_obj)session.qurey(table_cls).filter(condition).one()最后:session.commit()事物一定要提交,并且注意提交的时刻session.close()

sessionmaker 探讨

sessionmaker 顾名思义 是创建session的,其中,也可传递很多参数以满足不同需求

以下内容的代码均来自源码

  1. 第一个问题:sessionmaker 是什么?
    答:类

    class sessionmaker(_SessionClassMethods):def __init__(self, bind=None, class_=Session, autoflush=True,             autocommit=False,             expire_on_commit=True,             info=None, **kw):    kw['bind'] = bind    kw['autoflush'] = autoflush    kw['autocommit'] = autocommit    kw['expire_on_commit'] = expire_on_commit    if info is not None:        kw['info'] = info    self.kw = kw    # make our own subclass of the given class, so that    # events can be associated with it specifically.    self.class_ = type(class_.__name__, (class_,), {})def __call__(self, **local_kw):    """Produce a new :class:`.Session` object using the configuration    established in this :class:`.sessionmaker`.    In Python, the ``__call__`` method is invoked on an object when    it is "called" in the same way as a function::        Session = sessionmaker()        session = Session()  # invokes sessionmaker.__call__()    """    for k, v in self.kw.items():        if k == 'info' and 'info' in local_kw:            d = v.copy()            d.update(local_kw['info'])            local_kw['info'] = d        else:            local_kw.setdefault(k, v)    return self.class_(**local_kw)def configure(self, **new_kw):    """(Re)configure the arguments for this sessionmaker.    e.g.::        Session = sessionmaker()        Session.configure(bind=create_engine('sqlite://'))    """    self.kw.update(new_kw)def __repr__(self):    return "%s(class_=%r,%s)" % (        self.__class__.__name__,        self.class_.__name__,        ", ".join("%s=%r" % (k, v) for k, v in self.kw.items())    )
  2. sessionmaker() 返回值是什么
    是对象,type: sessionmaker

  3. sessionmaker()() 返回值是什么
    是一个继承自Session类的子类的对象,原因是self.class_ 是动态创建的Session的子类(默认)

    self.class_ = type(class_.__name__, (class_,), {})  # 通过type动态的生成了一个类,继承自class_,因为class_的默认值为Sessionreturn self.class_(**local_kw)
  4. session 支持的操作有哪些
    python
    public_methods = (
    '__contains__', '__iter__', 'add', 'add_all', 'begin', 'begin_nested',
    'close', 'commit', 'connection', 'delete', 'execute', 'expire',
    'expire_all', 'expunge', 'expunge_all', 'flush', 'get_bind',
    'is_modified', 'bulk_save_objects', 'bulk_insert_mappings',
    'bulk_update_mappings',
    'merge', 'query', 'refresh', 'rollback',
    'scalar')

补充:
__call__ 方法位于类中,标明此类的对象可直接调用
调用方式:class_object(args)

type 不仅仅可以获取对象的类型,同时还可以动态的创建类
使用方式:type(“class_name”, (object, …), **kwargs)
第一个参数为类名,第二个参数为父类元组,第三个对象为属性、方法(函数)

0 0
原创粉丝点击