在看源代码,看不懂一些类的定义,求点拨:

Endoresu 2016-01-28 10:40:55

nailgun/db/sqlalchemy/models/node.py
-----------------------------------------------------------------
88
89 class Node(Base):

304 @classmethod
305 def delete_by_ids(cls, ids):
306 db.query(Node).filter(Node.id.in_(ids)).delete('fetch')

32 from nailgun.db import db
--------------------------------------------------------------------


nailgun/db/sqlalchemy/__init__.py
-----------------------------------------------------------------------
80 db = scoped_session(
81 sessionmaker(
82 autoflush=True,
83 autocommit=False,
84 bind=engine,
85 query_cls=query_class,
86 class_=session_class
87 )
88 )
-----------------------------------------------------------------------


sqlalchemy/orm/scoping.py:
----------------------------------------------------------------------
class scoped_session(object):
"""Provides scoped management of :class:`.Session` objects.

See :ref:`unitofwork_contextual` for a tutorial.

"""

def __init__(self, session_factory, scopefunc=None):
"""Construct a new :class:`.scoped_session`.

:param session_factory: a factory to create new :class:`.Session`
instances. This is usually, but not necessarily, an instance
of :class:`.sessionmaker`.
:param scopefunc: optional function which defines
the current scope. If not passed, the :class:`.scoped_session`
object assumes "thread-local" scope, and will use
a Python ``threading.local()`` in order to maintain the current
:class:`.Session`. If passed, the function should return
a hashable token; this token will be used as the key in a
dictionary in order to store and retrieve the current
:class:`.Session`.

"""
self.session_factory = session_factory
if scopefunc:
self.registry = ScopedRegistry(session_factory, scopefunc)
else:
self.registry = ThreadLocalRegistry(session_factory)

def __call__(self, **kw):
"""Return the current :class:`.Session`, creating it
using the session factory if not present.

:param \**kw: Keyword arguments will be passed to the
session factory callable, if an existing :class:`.Session`
is not present. If the :class:`.Session` is present and
keyword arguments have been passed,
:exc:`~sqlalchemy.exc.InvalidRequestError` is raised.

"""
if kw:
scope = kw.pop('scope', False)
if scope is not None:
if self.registry.has():
raise sa_exc.InvalidRequestError(
"Scoped session is already present; "
"no new arguments may be specified.")
else:
sess = self.session_factory(**kw)
self.registry.set(sess)
return sess
else:
return self.session_factory(**kw)
else:
return self.registry()

def remove(self):
"""Dispose of the current :class:`.Session`, if present.

This will first call :meth:`.Session.close` method
on the current :class:`.Session`, which releases any existing
transactional/connection resources still being held; transactions
specifically are rolled back. The :class:`.Session` is then
discarded. Upon next usage within the same scope,
the :class:`.scoped_session` will produce a new
:class:`.Session` object.

"""

if self.registry.has():
self.registry().close()
self.registry.clear()

def configure(self, **kwargs):
"""reconfigure the :class:`.sessionmaker` used by this
:class:`.scoped_session`.

See :meth:`.sessionmaker.configure`.

"""

if self.registry.has():
warn('At least one scoped session is already present. '
' configure() can not affect sessions that have '
'already been created.')

self.session_factory.configure(**kwargs)

def query_property(self, query_cls=None):
"""return a class property which produces a :class:`.Query` object
against the class and the current :class:`.Session` when called.

e.g.::

Session = scoped_session(sessionmaker())

class MyClass(object):
query = Session.query_property()

# after mappers are defined
result = MyClass.query.filter(MyClass.name=='foo').all()

Produces instances of the session's configured query class by
default. To override and use a custom implementation, provide
a ``query_cls`` callable. The callable will be invoked with
the class's mapper as a positional argument and a session
keyword argument.

There is no limit to the number of query properties placed on
a class.

"""
class query(object):
def __get__(s, instance, owner):
try:
mapper = class_mapper(owner)
if mapper:
if query_cls:
# custom query class
return query_cls(mapper, session=self.registry())
else:
# session's configured query class
return self.registry().query(mapper)
except orm_exc.UnmappedClassError:
return None
return query()
------------------------------------------------------------------------------------------


我看不懂db.query()方法在是怎么定义的,以及filter()方法在哪定义的,在类sessionmaker和scoped_session没看到这些方法的定义,我想知道还有其它哪些方法,如何入手呢?


由于字数限制,类sessionmaker定义在下一楼。
...全文
254 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
panghuhu250 2016-01-29
  • 打赏
  • 举报
回复
看源码需要工具:

https://github.com/yinwang0/pysonar2, 能建立引用索引, 把代码变得可以像web一样浏览. 图发不上, 可以去github看.

ctags, grep等工具也有帮助.

wind% grep -r "def query" /usr/lib/python2.7/dist-packages/sqlalchemy/*
/usr/lib/python2.7/dist-packages/sqlalchemy/orm/scoping.py: def query_property(self, query_cls=None):
/usr/lib/python2.7/dist-packages/sqlalchemy/orm/session.py: def query(self, *entities, **kwargs):


(私货)我的一个半半成品:https://github.com/swiperthefox/python-source-browser, 基于ctags. 目前只有我一个用户,所以刚刚我自己够用就放下了.
Endoresu 2016-01-28
  • 打赏
  • 举报
回复
class _SessionClassMethods(object): """Class-level methods for :class:`.Session`, :class:`.sessionmaker`.""" @classmethod def close_all(cls): """Close *all* sessions in memory.""" for sess in _sessions.values(): sess.close() @classmethod @util.dependencies("sqlalchemy.orm.util") def identity_key(cls, orm_util, *args, **kwargs): """Return an identity key. This is an alias of :func:`.util.identity_key`. """ return orm_util.identity_key(*args, **kwargs) @classmethod def object_session(cls, instance): """Return the :class:`.Session` to which an object belongs. This is an alias of :func:`.object_session`. """ return object_session(instance)
Endoresu 2016-01-28
  • 打赏
  • 举报
回复
sqlalchemy/orm/session.py: -------------------------------------------------------------------------------------- class sessionmaker(_SessionClassMethods): """A configurable :class:`.Session` factory. The :class:`.sessionmaker` factory generates new :class:`.Session` objects when called, creating them given the configurational arguments established here. e.g.:: # global scope Session = sessionmaker(autoflush=False) # later, in a local scope, create and use a session: sess = Session() Any keyword arguments sent to the constructor itself will override the "configured" keywords:: Session = sessionmaker() # bind an individual session to a connection sess = Session(bind=connection) The class also includes a method :meth:`.configure`, which can be used to specify additional keyword arguments to the factory, which will take effect for subsequent :class:`.Session` objects generated. This is usually used to associate one or more :class:`.Engine` objects with an existing :class:`.sessionmaker` factory before it is first used:: # application starts Session = sessionmaker() # ... later engine = create_engine('sqlite:///foo.db') Session.configure(bind=engine) sess = Session() .. seealso: :ref:`session_getting` - introductory text on creating sessions using :class:`.sessionmaker`. """ def __init__(self, bind=None, class_=Session, autoflush=True, autocommit=False, expire_on_commit=True, info=None, **kw): """Construct a new :class:`.sessionmaker`. All arguments here except for ``class_`` correspond to arguments accepted by :class:`.Session` directly. See the :meth:`.Session.__init__` docstring for more details on parameters. :param bind: a :class:`.Engine` or other :class:`.Connectable` with which newly created :class:`.Session` objects will be associated. :param class_: class to use in order to create new :class:`.Session` objects. Defaults to :class:`.Session`. :param autoflush: The autoflush setting to use with newly created :class:`.Session` objects. :param autocommit: The autocommit setting to use with newly created :class:`.Session` objects. :param expire_on_commit=True: the expire_on_commit setting to use with newly created :class:`.Session` objects. :param info: optional dictionary of information that will be available via :attr:`.Session.info`. Note this dictionary is *updated*, not replaced, when the ``info`` parameter is specified to the specific :class:`.Session` construction operation. .. versionadded:: 0.9.0 :param \**kw: all other keyword arguments are passed to the constructor of newly created :class:`.Session` objects. """ 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()) ) ------------------------------------------------------------------------------------
内容概要:本文围绕“非线性流量的数据驱动Koopman模型预测控制研究”展开,提出一种基于数据驱动的Koopman算子理论方法,用于构建非线性系统的线性化状态空间模型,并结合模型预测控制(MPC)实现对复杂非线性系统的高效控制。研究通过引入扩展动态模态分解(EDMD)等观测函数,将非线性动力学映射至高维特征空间,在该空间中实现近似线性化表征,进而融合线性MPC框架进行优化解。全文系统阐述了Koopman算子的数学基础、隐式线性化机制及在非线性流量控制中的建模流程,并通过Matlab代码完成了算法实现与仿真实验,验证了该方法在处理无精确物理模型、强非线性、时变动态系统中的有效性与鲁棒性,尤其适用于工业流程控制、能源系统调度等实际工程场景。; 适合人群:具备自动控制理论、非线性系统分析基础,熟悉Matlab编程,从事控制工程、系统辨识、智能优化、能源系统建模等方向的研究生、科研人员及工程技术人员。; 使用场景及目标:①应用于难以建立精确数学模型的复杂非线性系统(如流体动力系统、电力电子系统、机器人动力学等)的建模与实时控制;②实现数据驱动下的模型预测控制,提升系统响应速度与控制精度;③为先进控制策略(如MPC)提供一种可行的线性化建模范式,推动现代控制理论与数据科学、机器学习的深度融合。; 阅读建议:建议读者结合提供的Matlab代码深入理解Koopman方法的具体实现过程,重点关注观测函数构造、核函数选择、矩阵逼近、降维处理及MPC控制器设计等关键技术环节,并尝试将其迁移至其他非线性系统中进行复现实验与性能对比,以全面掌握其适用范围与局限性。
内容概要:本文详细介绍了一种基于Simulink的光伏储能单相逆变器并网仿真模型,系统涵盖了光伏阵列、储能单元、DC-AC单相逆变器及并网接口的完整结构,重点实现了储能环节的能量管理与逆变器并网控制策略的建模仿真。通过Simulink平台构建系统模型,验证了逆变器输出电能质量、并网稳定性以及控制系统的动态响应性能,采用SPWM调制、PI闭环控制等关键技术,确保并网电流与电网电压同频同相,满足并网电能质量要。该模型不仅可用于分布式能源系统的仿真研究,还可作为新能源并网技术的教学与工程实践工具。; 适合人群:电气工程、自动化、新能源科学与工程等相关专业的高校本科生、研究生、科研人员,以及从事光伏发电系统设计、储能控制与并网技术研发的工程技术人员。; 使用场景及目标:①深入理解光伏储能系统中能量转换、存储与并网控制的整体工作原理;②支持课程设计、毕业设计或科研项目中对单相逆变器控制策略(如SPWM、PI调节、锁相技术等)的仿真验证与参数优化;③为后续研究更复杂的控制算法(如MPPT、低电压穿越、谐波抑制等)提供可扩展的仿真基础平台。; 阅读建议:建议结合MATLAB/Simulink环境动手搭建与调试模型,逐步理解各模块(如光伏建模、储能充放电控制、逆变器驱动、锁相环、PI调节器等)的功能与交互关系,重点关注控制系统的设计逻辑与参数整定过程,并可通过修改负载条件或电网参数测试系统鲁棒性,为进一步拓展至三相系统或多机并网场景奠定基础。

37,741

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧