• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python session.object_session函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sqlalchemy.orm.session.object_session函数的典型用法代码示例。如果您正苦于以下问题:Python object_session函数的具体用法?Python object_session怎么用?Python object_session使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了object_session函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: get_token_for_calendars_restrict_ids

    def get_token_for_calendars_restrict_ids(self, account, client_ids,
                                             force_refresh=False):
        '''
        For the given account, returns an access token that's associated
        with a client id from the given list of client_ids.
        '''
        scope = GOOGLE_CALENDAR_SCOPE
        if not force_refresh:
            try:
                gtoken = self._tokens[account.id][scope]
                if gtoken.client_id in client_ids:
                    return gtoken.value
            except KeyError:
                pass

        # Need to get access token for specific client_id/client_secret pair
        try:
            gtoken = account.new_token(
                    scope, client_ids=client_ids)
        except (ConnectionError, OAuthError):
            object_session(account).commit()
            raise

        self.cache_token(account, gtoken)
        return gtoken.value
开发者ID:Eagles2F,项目名称:sync-engine,代码行数:25,代码来源:gmail.py


示例2: new_bin

    def new_bin(self, batch):

        bin = Bin()
        bin.marker_id = self.id
        bin.batch_id = batch.id
        object_session(self).add(bin)
        return bin
开发者ID:edawine,项目名称:fatools,代码行数:7,代码来源:schema.py


示例3: _get_token

    def _get_token(self, account, scope, force_refresh=False):
        if not force_refresh:
            try:
                gtoken = self._tokens[account.id][scope]
                if datetime.utcnow() < gtoken.expiration:
                    return gtoken
            except KeyError:
                pass

        # If we find invalid GmailAuthCredentials while trying to
        # get a new token, we mark them as invalid. We want to make
        # sure we commit those changes to the database before we
        # actually throw an error.
        try:
            gtoken = account.new_token(scope)
        except (ConnectionError, OAuthError):
            if object_session(account):
                object_session(account).commit()
            else:
                with session_scope(account.id) as db_session:
                    db_session.merge(account)
                    db_session.commit()
            raise

        self.cache_token(account, gtoken)
        return gtoken
开发者ID:GordonYip,项目名称:sync-engine,代码行数:26,代码来源:gmail.py


示例4: add_statement

 def add_statement(self, phase, time, value):
     statement = Statement()
     statement.user = self
     statement.phase = phase
     statement.time = time
     statement.value = value
     object_session(self).add(statement)
开发者ID:giomasce,项目名称:mensa,代码行数:7,代码来源:data.py


示例5: _delete

 def _delete(self):
     """Remove image scale from database and filesystem.
     """
     try:
         delete_file(self.filesystem_path)
     except OSError as e:
         if e.errno != errno.ENOENT:
             raise
     object_session(self).delete(self)
开发者ID:curvetips,项目名称:s4u.image,代码行数:9,代码来源:model.py


示例6: delete

 def delete(self):
     """Delete this image including all scales from the database and disk.
     """
     self._delete_scales()
     try:
         delete_file(self.filesystem_path)
     except OSError as e:
         if e.errno != errno.ENOENT:
             raise
     object_session(self).delete(self)
开发者ID:curvetips,项目名称:s4u.image,代码行数:10,代码来源:model.py


示例7: active_ballot_events

    def active_ballot_events(self):
        # this needs to be guarded in the function, as it's circular
        from . import BallotEvent

        if not object_session(self):
            return {}

        all_events = object_session(self).query(BallotEvent).filter(BallotEvent.is_active).all()

        return { e: self.slot_for.get(e) for e in all_events }
开发者ID:eric-wieser,项目名称:caius-rooms,代码行数:10,代码来源:person.py


示例8: create_thumbnail

 def create_thumbnail(self, size=(500, 333)):
     _, thumbnail_filename = create_thumbnail(self.fullpath, size)
     folder, filename = os.path.split(thumbnail_filename)
     thumbnail = Thumbnail(
         image_id=self.id, 
         width=size[0], 
         height=size[1], 
         folder=folder, 
         filename=filename
     )
     object_session(self).add(thumbnail)
     object_session(self).commit()
开发者ID:hamstah,项目名称:clouddream,代码行数:12,代码来源:models.py


示例9: __init__

    def __init__(self, model=None, parent=None, branch_mode=False):
        '''
        :param model: Plant instance or None
        :param parent: None
        :param branch_mode:
        '''
        if branch_mode:
            if model is None:
                raise CheckConditionError(_("branch_mode requires a model"))
            elif object_session(model) and model in object_session(model).new:
                raise CheckConditionError(_("cannot branch a new plant"))

        # TODO: shouldn't allow branching plants with quantity < 2
        # TODO: shouldn't allow changing the accession code in branch_mode

        if model is None:
            model = Plant()

        self.branched_plant = None
        if branch_mode:
            # duplicate the model so we can branch from it without
            # destroying the first
            self.branched_plant = model
            model = self.branched_plant.duplicate(code=None)

        super(PlantEditor, self).__init__(model, parent)

        if self.branched_plant:
            # make a copy of the branched plant for this session
            self.branched_plant = self.session.merge(self.branched_plant)

        if not parent and bauble.gui:
            parent = bauble.gui.window
        self.parent = parent
        self._committed = []

        view = PlantEditorView(parent=self.parent)
        self.presenter = PlantEditorPresenter(self.model, view)

        # add quick response keys
        self.attach_response(view.get_window(), gtk.RESPONSE_OK, 'Return',
                             gtk.gdk.CONTROL_MASK)
        self.attach_response(view.get_window(), self.RESPONSE_NEXT, 'n',
                             gtk.gdk.CONTROL_MASK)

        # set default focus
        if self.model.accession is None:
            view.widgets.plant_acc_entry.grab_focus()
        else:
            view.widgets.plant_code_entry.grab_focus()
开发者ID:Jean-FrancoisGagnon,项目名称:bauble.classic,代码行数:50,代码来源:plant.py


示例10: vmcreate

def vmcreate(e):
    tenant = e.tenant
    msg = e.payload
    session = object_session(tenant)
    svc = tenant.getservicebyname(msg.vmType)

    if svc is None:
        logger.error("for node(%s/%s/%s) can not find corresponding service db object" % (tenant.id,msg.vmType,msg.stackid))
        return

    logger.info("part sync start.accountId<%s>" % tenant.id)
    ctx = ServiceContext()
    zk_host = ctx.getConfigService().get("Inventory","zk_address")
    account_sync(tenant.id,zk_host)
    logger.info("part sync finished.accountId<%s>" % tenant.id)
    node = svc.createnode()
    node.stackid = msg.stackId
    node.vmtype = msg.vmType
    node.manageip = msg.vmManagementIP
    node.publicip = msg.vmPublicIP
    node.serviceip = msg.vmServiceIP
    session.add(node)
    session.commit()
    logger.info("node(%s/%s/%s) has been created in db" % (tenant.id,node.vmtype,node.stackid))
    flag = True
    for svc in tenant.services:
        flag = flag and svc.isready()

    tenant.state = e.fsm.current

    if flag:
        tenant.getSM().trigger("create_vm_done",tenant = tenant)
开发者ID:codebang,项目名称:dms-sa,代码行数:32,代码来源:tenantsm.py


示例11: save

 def save(self, commit=True):
     """Save the record."""
     db = object_session(self)
     db.add(self)
     if commit:
         db.commit()
     return self
开发者ID:spinningD20,项目名称:kivy_rpg,代码行数:7,代码来源:models.py


示例12: __init__

    def __init__(self, model, view):
        '''
        :param model: should be an instance of class Family
        :param view: should be an instance of FamilyEditorView
        '''
        super(FamilyEditorPresenter, self).__init__(model, view)
        self.session = object_session(model)

        # initialize widgets
        self.init_enum_combo('fam_qualifier_combo', 'qualifier')
        self.synonyms_presenter = SynonymsPresenter(self)
        self.refresh_view() # put model values in view

        # connect signals
        self.assign_simple_handler('fam_family_entry', 'family',
                                   editor.UnicodeOrNoneValidator())
        self.assign_simple_handler('fam_qualifier_combo', 'qualifier',
                                   editor.UnicodeOrEmptyValidator())

        notes_parent = self.view.widgets.notes_parent_box
        notes_parent.foreach(notes_parent.remove)
        self.notes_presenter = \
            editor.NotesPresenter(self, 'notes', notes_parent)

        if self.model not in self.session.new:
            self.view.widgets.fam_ok_and_add_button.set_sensitive(True)

        # for each widget register a signal handler to be notified when the
        # value in the widget changes, that way we can do things like sensitize
        # the ok button
        self.__dirty = False
开发者ID:Jean-FrancoisGagnon,项目名称:bauble.classic,代码行数:31,代码来源:family.py


示例13: pages

 def pages(self):
     """ Return all translations that have this file in its relation """
     session = object_session(self)
     attr = getattr(PageInfo, "{}s".format(self.__class__.__name__.lower()))
     return session.query(PageInfo).filter(
             attr.any(self.__class__.id == self.id)
     ).all()
开发者ID:asidev,项目名称:aybu-core,代码行数:7,代码来源:file.py


示例14: onEnter

    def onEnter(self, dbcluster):
        dbdecommissioned = HostLifecycle.get_unique(object_session(dbcluster),
                                                    "decommissioned",
                                                    compel=True)

        config = Config()
        archetype = dbcluster.personality.archetype
        section = "archetype_" + archetype.name
        opt = "allow_cascaded_deco"

        if dbcluster.hosts and (not config.has_option(section, opt) or
                                not config.getboolean(section, opt)):
            raise ArgumentError("Cannot change state to {0}, as {1}'s "
                                "archetype is {2}."
                                .format(dbdecommissioned.name, dbcluster,
                                        archetype.name))

        if dbcluster.virtual_machines:
            raise ArgumentError("Cannot change state to {0}, as {1} has "
                                "{2} VM(s)."
                                .format(dbdecommissioned.name, dbcluster,
                                        len(dbcluster.virtual_machines)))

        for dbhost in dbcluster.hosts:
            dbhost.status.transition(dbhost, dbdecommissioned)
开发者ID:piojo,项目名称:aquilon,代码行数:25,代码来源:clusterlifecycle.py


示例15: new_channel

    def new_channel(self, raw_data, data, dye, wavelen, status, median, mean,
            max_height, min_height, std_dev, initial_marker=None, initial_panel=None):
        """ create new channel and added to this assay """
        if not initial_marker:
            initial_marker = Marker.search('undefined', session = object_session(self))
        if not initial_panel:
            initial_panel = Panel.search('undefined', session = object_session(self))
        channel = Channel( raw_data = data, data = data, dye = dye, wavelen = wavelen,
                            status = status, median = median, mean = mean,
                            max_height = max_height, min_height = min_height,
                            std_dev = std_dev )
        channel.fsa = self
        channel.marker = initial_marker
        channel.panel = initial_panel

        return channel
开发者ID:edawine,项目名称:fatools,代码行数:16,代码来源:schema.py


示例16: monitorcpe

def monitorcpe(e):
    tenant = e.tenant
    job = JobBuilder.buildmonitorcpejob(tenant)
    rundeck_client = ServiceContext().getRdClient()
    session = object_session(tenant)
    if job is None:
        logger.error("monitor cpe job build failded")
        return
    try:
        rundeck_reponse = rundeck_client.import_job(job.to_xml(),fmt = "xml", dupeOption = "create" , project = "dms-sa", uuidOption = "remove")
    except:
        logger.error("import account(%s) job failed, for connection reason" % tenant.id)
        session.flush()
        return

    if rundeck_reponse['failed'] == None and rundeck_reponse['skipped'] == None:
        print rundeck_reponse
        id = rundeck_reponse['succeeded'][0]["id"]
        name = rundeck_reponse['succeeded'][0]["name"]
        rdjob = job.node.createrdjob(name,id)
        session.add(rdjob)
        try:
            ret = rundeck_client.run_job(rdjob.jobid)
        except Exception,e:
            logger.error("runjob (%s) error (%s)" % (rdjob.jobid,e.message))
        else:
            status = ret['status']
            if status == 'falied':
                rdjob.jobstate = "runerror"
                href = ret["href"]
                logger.error("job run error , the execution link: (%s)" % href)
            else:
                rdjob.jobstate = "runsuccess"
        session.flush()
开发者ID:codebang,项目名称:dms-sa,代码行数:34,代码来源:tenantsm.py


示例17: get_bind

def get_bind(obj):
    """
    Return the bind for given SQLAlchemy Engine / Connection / declarative
    model object.

    :param obj: SQLAlchemy Engine / Connection / declarative model object

    ::

        from sqlalchemy_utils import get_bind


        get_bind(session)  # Connection object

        get_bind(user)

    """
    if hasattr(obj, 'bind'):
        conn = obj.bind
    else:
        try:
            conn = object_session(obj).bind
        except UnmappedInstanceError:
            conn = obj

    if not hasattr(conn, 'execute'):
        raise TypeError(
            'This method accepts only Session, Engine, Connection and '
            'declarative model objects.'
        )
    return conn
开发者ID:rpk,项目名称:sqlalchemy-utils,代码行数:31,代码来源:orm.py


示例18: get_or_create_execution

    def get_or_create_execution(self, color, group):
        colors = group.get('color_lineage', []) + [color]
        begins = group.get('begin_lineage', []) + [group['begin']]
        parent_color = _get_parent_color(colors)

        s = object_session(self)

        try:
            return s.query(MethodExecution).filter(
                    MethodExecution.method==self,
                    MethodExecution.color==color).one()
        except NoResultFound:
            execution = MethodExecution(method=self, color=color,
                    colors=colors, begins=begins,
                    parent_color=parent_color,
                    workflow_id=self.workflow_id,
            )
            s.add(execution)

            try:
                s.commit()
                return execution
            except IntegrityError:
                s.rollback()
                return s.query(MethodExecution).filter(
                        MethodExecution.method==self,
                        MethodExecution.color==color).one()
开发者ID:davidlmorton,项目名称:ptero-workflow,代码行数:27,代码来源:method_base.py


示例19: remove_callback

def remove_callback(families):
    """
    The callback function to remove a family from the family context menu.
    """
    family = families[0]
    from bauble.plugins.plants.genus import Genus
    session = object_session(family)
    ngen = session.query(Genus).filter_by(family_id=family.id).count()
    safe_str = utils.xml_safe(str(family))
    if ngen > 0:
        msg = _('The family <i>%(family)s</i> has %(num_genera)s genera.  Are '
                'you sure you want to remove it?') % dict(family=safe_str,
                                                          num_genera=ngen)
    else:
        msg = _("Are you sure you want to remove the family <i>%s</i>?") \
            % safe_str
    if not utils.yes_no_dialog(msg):
        return
    try:
        obj = session.query(Family).get(family.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _('Could not delete.\n\n%s') % utils.xml_safe(e)
        utils.message_details_dialog(msg, traceback.format_exc(),
                                     type=gtk.MESSAGE_ERROR)
开发者ID:Ghini,项目名称:ghini.desktop,代码行数:26,代码来源:family.py


示例20: create_execution

    def create_execution(self, body_data, query_string_data):
        color = body_data['color']
        response_links = body_data['response_links']
        s = object_session(self)

        try:
            execution = s.query(TaskExecution).filter(
                    TaskExecution.task==self,
                    TaskExecution.color==color).one()
        except NoResultFound:
            group = body_data['group']

            colors = group.get('color_lineage', []) + [color]
            begins = group.get('begin_lineage', []) + [group['begin']]
            parent_color = _get_parent_color(colors)

            execution = TaskExecution(task=self, color=color,
                    colors=colors, begins=begins,
                    parent_color=parent_color, data={
                        'petri_response_links': response_links,
            })
            execution.status = statuses.scheduled
            execution.status = statuses.running
            s.add(execution)

        if self.is_canceled:
            execution.status = statuses.canceled

        s.commit()

        self.http.delay('PUT', response_links['created'])
开发者ID:iferguson90,项目名称:ptero-workflow,代码行数:31,代码来源:task_base.py



注:本文中的sqlalchemy.orm.session.object_session函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python session.sessionmaker函数代码示例发布时间:2022-05-27
下一篇:
Python session.make_transient函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap