当前位置: 首页>>代码示例>>Python>>正文


Python sqlalchemy.update方法代码示例

本文整理汇总了Python中sqlalchemy.update方法的典型用法代码示例。如果您正苦于以下问题:Python sqlalchemy.update方法的具体用法?Python sqlalchemy.update怎么用?Python sqlalchemy.update使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sqlalchemy的用法示例。


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

示例1: update_invitation

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import update [as 别名]
def update_invitation(request: web.Request, params: Any) -> web.Response:
    '''
    Update sent invitation's permission. Other fields are not allowed to be updated.
    '''
    dbpool = request.app['dbpool']
    access_key = request['keypair']['access_key']
    inv_id = request.match_info['inv_id']
    perm = params['perm']
    log.info('VFOLDER.UPDATE_INVITATION (ak:{}, inv:{})', access_key, inv_id)
    async with dbpool.acquire() as conn:
        query = (sa.update(vfolder_invitations)
                   .values(permission=perm)
                   .where(vfolder_invitations.c.id == inv_id)
                   .where(vfolder_invitations.c.inviter == request['user']['email'])
                   .where(vfolder_invitations.c.state == VFolderInvitationState.PENDING))
        await conn.execute(query)
    resp = {'msg': f'vfolder invitation updated: {inv_id}.'}
    return web.json_response(resp, status=200) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:20,代码来源:vfolder.py

示例2: upgrade

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import update [as 别名]
def upgrade():
    op.add_column('keypairs', sa.Column('ssh_public_key', sa.String(length=750), nullable=True))
    op.add_column('keypairs', sa.Column('ssh_private_key', sa.String(length=2000), nullable=True))

    # partial table to be preserved and referred
    metadata = sa.MetaData(naming_convention=convention)
    keypairs = sa.Table(
        'keypairs', metadata,
        sa.Column('access_key', sa.String(length=20), primary_key=True),
        sa.Column('ssh_public_key', sa.String(length=750), nullable=True),
        sa.Column('ssh_private_key', sa.String(length=2000), nullable=True),
    )

    # Fill in SSH keypairs in every keypairs.
    conn = op.get_bind()
    query = sa.select([keypairs.c.access_key]).select_from(keypairs)
    rows = conn.execute(query).fetchall()
    for row in rows:
        pubkey, privkey = generate_ssh_keypair()
        query = (sa.update(keypairs)
                   .values(ssh_public_key=pubkey, ssh_private_key=privkey)
                   .where(keypairs.c.access_key == row.access_key))
        conn.execute(query) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:25,代码来源:0262e50e90e0_add_ssh_keypair_into_keypair.py

示例3: recalc_concurrency_used

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import update [as 别名]
def recalc_concurrency_used(db_conn: SAConnection, access_key: AccessKey) -> None:
    query = (
        sa.update(keypairs)
        .values(
            concurrency_used=(
                sa.select([sa.func.count(kernels.c.id)])
                .select_from(kernels)
                .where(
                    (kernels.c.access_key == access_key) &
                    (kernels.c.status.in_(USER_RESOURCE_OCCUPYING_KERNEL_STATUSES))
                )
                .as_scalar()
            ),
        )
        .where(keypairs.c.access_key == access_key)
    )
    await db_conn.execute(query) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:19,代码来源:kernel.py

示例4: _unreserve_agent_slots

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import update [as 别名]
def _unreserve_agent_slots(
    db_conn: SAConnection,
    sess_ctx: PendingSession,
    agent_ctx: AgentAllocationContext,
) -> None:
    # Un-reserve agent slots, using a separate db txn.
    query = (
        sa.select([agents.c.occupied_slots], for_update=True)
        .select_from(agents)
        .where(agents.c.id == agent_ctx.agent_id))
    current_occupied_slots = await db_conn.scalar(query)
    query = (
        sa.update(agents)
        .values({
            'occupied_slots': current_occupied_slots - sess_ctx.requested_slots
        })
        .where(agents.c.id == agent_ctx.agent_id))
    await db_conn.execute(query) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:20,代码来源:dispatcher.py

示例5: set_kernel_status

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import update [as 别名]
def set_kernel_status(self, kernel_id: KernelId,
                                status: KernelStatus,
                                reason: str = '', *,
                                db_conn: SAConnection = None):
        assert status != KernelStatus.TERMINATED, \
               'TERMINATED status update must be handled in ' \
               'mark_kernel_terminated()'
        data = {
            'status': status,
            'status_info': reason,
            'status_changed': datetime.now(tzutc()),
        }
        async with reenter_txn(self.dbpool, db_conn) as conn:
            query = (
                sa.update(kernels)
                .values(data)
                .where(kernels.c.id == kernel_id)
            )
            await conn.execute(query) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:21,代码来源:registry.py

示例6: delete

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import update [as 别名]
def delete(request: web.Request, params: Any) -> web.Response:
    dbpool = request.app['dbpool']
    template_id = request.match_info['template_id']

    requester_access_key, owner_access_key = await get_access_key_scopes(request, params)
    log.info('DELETE (ak:{0}/{1})',
             requester_access_key, owner_access_key if owner_access_key != requester_access_key else '*')

    async with dbpool.acquire() as conn, conn.begin():
        query = (sa.select([session_templates.c.id])
                   .select_from(session_templates)
                   .where((session_templates.c.id == template_id) &
                          (session_templates.c.is_active)
                          ))
        result = await conn.scalar(query)
        if not result:
            raise TaskTemplateNotFound

        query = (sa.update(session_templates)
                   .values(is_active=False)
                   .where((session_templates.c.id == template_id)))
        result = await conn.execute(query)
        assert result.rowcount == 1

        return web.json_response({'success': True}) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:27,代码来源:session_template.py

示例7: touch_collection_replicas

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import update [as 别名]
def touch_collection_replicas(collection_replicas, session=None):
    """
    Update the accessed_at timestamp of the given collection replicas.

    :param collection_replicas: the list of collection replicas.
    :param session: The database session in use.

    :returns: True, if successful, False otherwise.
    """

    now = datetime.utcnow()
    for collection_replica in collection_replicas:
        try:
            session.query(models.CollectionReplica).filter_by(scope=collection_replica['scope'], name=collection_replica['name'], rse_id=collection_replica['rse_id']).\
                update({'accessed_at': collection_replica.get('accessed_at') or now}, synchronize_session=False)
        except DatabaseError:
            return False

    return True 
开发者ID:rucio,项目名称:rucio,代码行数:21,代码来源:replica.py

示例8: set_tombstone

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import update [as 别名]
def set_tombstone(rse_id, scope, name, tombstone=OBSOLETE, session=None):
    """
    Sets a tombstone on a replica.

    :param rse_id: ID of RSE.
    :param scope: scope of the replica DID.
    :param name: name of the replica DID.
    :param tombstone: the tombstone to set. Default is OBSOLETE
    :param session: database session in use.
    """
    stmt = update(models.RSEFileAssociation).where(and_(models.RSEFileAssociation.rse_id == rse_id, models.RSEFileAssociation.name == name, models.RSEFileAssociation.scope == scope,
                                                        ~session.query(models.ReplicaLock).filter_by(scope=scope, name=name, rse_id=rse_id).exists()))\
                                            .values(tombstone=tombstone)
    result = session.execute(stmt)
    if not result.rowcount:
        try:
            session.query(models.RSEFileAssociation).filter_by(scope=scope, name=name, rse_id=rse_id).one()
            raise exception.ReplicaIsLocked('Replica %s:%s on RSE %s is locked.' % (scope, name, get_rse_name(rse_id=rse_id, session=session)))
        except NoResultFound:
            raise exception.ReplicaNotFound('Replica %s:%s on RSE %s could not be found.' % (scope, name, get_rse_name(rse_id=rse_id, session=session))) 
开发者ID:rucio,项目名称:rucio,代码行数:22,代码来源:replica.py

示例9: set_requests_state

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import update [as 别名]
def set_requests_state(request_ids, new_state, session=None):
    """
    Bulk update the state of requests. Fails silently if the request_id does not exist.

    :param request_ids:  List of (Request-ID as a 32 character hex string).
    :param new_state:    New state as string.
    :param session:      Database session to use.
    """

    record_counter('core.request.set_requests_state')

    try:
        for request_id in request_ids:
            set_request_state(request_id, new_state, session=session)
    except IntegrityError as error:
        raise RucioException(error.args) 
开发者ID:rucio,项目名称:rucio,代码行数:18,代码来源:request.py

示例10: touch_requests_by_rule

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import update [as 别名]
def touch_requests_by_rule(rule_id, session=None):
    """
    Update the update time of requests in a rule. Fails silently if no requests on this rule.

    :param rule_id:  Rule-ID as a 32 character hex string.
    :param session:  Database session to use.
    """

    record_counter('core.request.touch_requests_by_rule')

    try:
        session.query(models.Request).with_hint(models.Request, "INDEX(REQUESTS REQUESTS_RULEID_IDX)", 'oracle')\
                                     .filter_by(rule_id=rule_id)\
                                     .filter(models.Request.state.in_([RequestState.FAILED, RequestState.DONE, RequestState.LOST, RequestState.NO_SOURCES, RequestState.ONLY_TAPE_SOURCES]))\
                                     .filter(models.Request.updated_at < datetime.datetime.utcnow())\
                                     .update({'updated_at': datetime.datetime.utcnow() + datetime.timedelta(minutes=20)}, synchronize_session=False)
    except IntegrityError as error:
        raise RucioException(error.args) 
开发者ID:rucio,项目名称:rucio,代码行数:20,代码来源:request.py

示例11: release_waiting_requests_per_deadline

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import update [as 别名]
def release_waiting_requests_per_deadline(rse_id=None, deadline=1, session=None):
    """
    Release waiting requests that were waiting too long and exceeded the maximum waiting time to be released.
    If the DID of a request is attached to a dataset, the oldest requested_at date of all requests related to the dataset will be used for checking and all requests of this dataset will be released.
    :param rse_id:           The source RSE id.
    :param deadline:         Maximal waiting time in hours until a dataset gets released.
    :param session:          The database session.
    """
    amount_released_requests = 0
    if deadline:
        grouped_requests_subquery, filtered_requests_subquery = create_base_query_grouped_fifo(rse_id, filter_by_rse='source', session=session)
        old_requests_subquery = session.query(grouped_requests_subquery.c.name,
                                              grouped_requests_subquery.c.scope,
                                              grouped_requests_subquery.c.oldest_requested_at)\
                                       .filter(grouped_requests_subquery.c.oldest_requested_at < datetime.datetime.now() - datetime.timedelta(hours=deadline))\
                                       .subquery()
        old_requests_subquery = session.query(filtered_requests_subquery.c.id)\
                                       .join(old_requests_subquery, and_(filtered_requests_subquery.c.dataset_name == old_requests_subquery.c.name, filtered_requests_subquery.c.dataset_scope == old_requests_subquery.c.scope))
        old_requests_subquery = old_requests_subquery.subquery()
        statement = update(models.Request).where(models.Request.id.in_(old_requests_subquery)).values(state=RequestState.QUEUED)
        amount_released_requests = session.execute(statement).rowcount
    return amount_released_requests 
开发者ID:rucio,项目名称:rucio,代码行数:24,代码来源:request.py

示例12: __touch_request

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import update [as 别名]
def __touch_request(request_id, session=None):
    """
    Update the timestamp of a request. Fails silently if the request_id does not exist.

    :param request_id:  Request-ID as a 32 character hex string.
    :param session:     Database session to use.
    """

    record_counter('core.request.touch_request')

    try:
        rowcount = session.query(models.Request).filter_by(id=request_id).update({'updated_at': datetime.datetime.utcnow()}, synchronize_session=False)
    except IntegrityError as error:
        raise RucioException(error.args)
    if not rowcount:
        raise UnsupportedOperation("Request %s cannot be touched." % request_id) 
开发者ID:rucio,项目名称:rucio,代码行数:18,代码来源:request.py

示例13: __init__

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import update [as 别名]
def __init__(self, table, name):
        self.table = table
        self.name = name
        self.info = {}

        if name is not None:
            op = self.table.migration.operation
            with cnx(self.table.migration) as conn:
                columns = op.impl.dialect.get_columns(
                    conn, self.table.name, schema=table.schema)

            for c in columns:
                if c['name'] == name:
                    self.info.update(c)

            if not self.info:
                raise MigrationException(
                    "No column %r found on %r" % (name, self.table.name)) 
开发者ID:AnyBlok,项目名称:AnyBlok,代码行数:20,代码来源:migration.py

示例14: reschedule

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import update [as 别名]
def reschedule(self, name):
            state = yield from self.get(name)
            if state.manual:
                raise ValueError("Can't reschedule")
            else:
                local_offset = pytz.timezone(state.timezone).utcoffset(dt.datetime.utcnow())
                cron = croniter(state.crontab, dt.datetime.utcnow() + local_offset)
                reschedule = cron.get_next(dt.datetime) - local_offset

            with (yield from self.db.engine) as conn:
                yield from conn.execute(update(
                    Job.__table__
                ).where(
                    Job.name==name
                ).values(
                    active=True,
                    scheduled=reschedule,
                )) 
开发者ID:paultag,项目名称:moxie,代码行数:20,代码来源:database.py

示例15: take

# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import update [as 别名]
def take(self, name):
            state = yield from self.get(name)
            if state.active == True:
                raise ValueError("In progress already")

            with (yield from self.db.engine) as conn:
                if state.manual is False:
                    yield from self.reschedule(name)

                result = yield from conn.execute(update(
                    Job.__table__
                ).where(
                    Job.name==name
                ).values(
                    active=True
                )) 
开发者ID:paultag,项目名称:moxie,代码行数:18,代码来源:database.py


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