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


Python session.Session方法代码示例

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


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

示例1: add_token

# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import Session [as 别名]
def add_token(request: LocalProxy, session: Session) -> str:
    """
    Create a new token for the user or return a
    valid existing token to the user.
    """
    token = None
    id_ = int(request.authorization['username'])
    try:
        token = session.query(Token).filter(Token.user_id == id_).one()
        if not token.is_valid():
            update_token = '%030x' % randrange(16**30)
            token.id = update_token
            token.timestamp = datetime.now()
            session.commit()
    except NoResultFound:
        token = '%030x' % randrange(16**30)
        new_token = Token(user_id=id_, id=token)
        session.add(new_token)
        session.commit()
        return token
    return token.id 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:23,代码来源:user.py

示例2: set_session

# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import Session [as 别名]
def set_session(application: Flask, DB_SESSION: scoped_session) -> Iterator:
    """
    Set the Database Session for the app before it is run in main.py.
    :param application: Flask app object
            <flask.app.Flask>
    :param DB_SESSION: SQLalchemy Session object
            <sqlalchemy.orm.session.Session>

    Raises:
        TypeError: If `DB_SESSION` is not an instance of `scoped_session` or `Session`.

    """
    if not isinstance(DB_SESSION, scoped_session) and not isinstance(
            DB_SESSION, Session):
        raise TypeError(
            "The API Doc is not of type <sqlalchemy.orm.session.Session> or"
            " <sqlalchemy.orm.scoping.scoped_session>")

    def handler(sender: Flask, **kwargs: Any) -> None:
        g.dbsession = DB_SESSION
    with appcontext_pushed.connected_to(handler, application):
        yield 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:24,代码来源:utils.py

示例3: setup

# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import Session [as 别名]
def setup(self):
        self.mock_sess = Mock(spec_set=Session)
        self.cls = BiweeklyPayPeriod(date(2017, 3, 7), self.mock_sess)
        m_account = Mock(name='foo')
        type(m_account).name = 'foo'
        m_budget = Mock(name='bar')
        type(m_budget).name = 'bar'
        self.m_st = Mock(
            spec_set=ScheduledTransaction,
            id=123,
            description='desc',
            amount=Decimal('123.45'),
            account_id=2,
            account=m_account,
            budget_id=3,
            budget=m_budget
        ) 
开发者ID:jantman,项目名称:biweeklybudget,代码行数:19,代码来源:test_biweeklypayperiod.py

示例4: get_xcom_entry

# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import Session [as 别名]
def get_xcom_entry(
    dag_id: str,
    task_id: str,
    dag_run_id: str,
    xcom_key: str,
    session: Session
) -> XComCollectionItemSchema:
    """
    Get an XCom entry
    """
    query = session.query(XCom)
    query = query.filter(and_(XCom.dag_id == dag_id,
                              XCom.task_id == task_id,
                              XCom.key == xcom_key))
    query = query.join(DR, and_(XCom.dag_id == DR.dag_id, XCom.execution_date == DR.execution_date))
    query = query.filter(DR.run_id == dag_run_id)

    query_object = query.one_or_none()
    if not query_object:
        raise NotFound("XCom entry not found")
    return xcom_collection_item_schema.dump(query_object) 
开发者ID:apache,项目名称:airflow,代码行数:23,代码来源:xcom_endpoint.py

示例5: get_previous_dagrun

# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import Session [as 别名]
def get_previous_dagrun(self, state: Optional[str] = None, session: Session = None) -> Optional['DagRun']:
        """The previous DagRun, if there is one"""

        session = cast(Session, session)  # mypy

        filters = [
            DagRun.dag_id == self.dag_id,
            DagRun.execution_date < self.execution_date,
        ]
        if state is not None:
            filters.append(DagRun.state == state)
        return session.query(DagRun).filter(
            *filters
        ).order_by(
            DagRun.execution_date.desc()
        ).first() 
开发者ID:apache,项目名称:airflow,代码行数:18,代码来源:dagrun.py

示例6: _are_premature_tis

# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import Session [as 别名]
def _are_premature_tis(
        self,
        unfinished_tasks: List[TI],
        finished_tasks: List[TI],
        session: Session,
    ) -> bool:
        # there might be runnable tasks that are up for retry and for some reason(retry delay, etc) are
        # not ready yet so we set the flags to count them in
        for ut in unfinished_tasks:
            if ut.are_dependencies_met(
                dep_context=DepContext(
                    flag_upstream_failed=True,
                    ignore_in_retry_period=True,
                    ignore_in_reschedule_period=True,
                    finished_tasks=finished_tasks),
                    session=session):
                return True
        return False 
开发者ID:apache,项目名称:airflow,代码行数:20,代码来源:dagrun.py

示例7: get_paused_dag_ids

# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import Session [as 别名]
def get_paused_dag_ids(dag_ids: List[str], session: Session = None) -> Set[str]:
        """
        Given a list of dag_ids, get a set of Paused Dag Ids

        :param dag_ids: List of Dag ids
        :param session: ORM Session
        :return: Paused Dag_ids
        """
        paused_dag_ids = (
            session.query(DagModel.dag_id)
            .filter(DagModel.is_paused.is_(True))
            .filter(DagModel.dag_id.in_(dag_ids))
            .all()
        )

        paused_dag_ids = set(paused_dag_id for paused_dag_id, in paused_dag_ids)
        return paused_dag_ids 
开发者ID:apache,项目名称:airflow,代码行数:19,代码来源:dag.py

示例8: running_slots

# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import Session [as 别名]
def running_slots(self, session: Session):
        """
        Get the number of slots used by running tasks at the moment.

        :param session: SQLAlchemy ORM Session
        :return: the used number of slots
        """
        from airflow.models.taskinstance import TaskInstance  # Avoid circular import

        return (
            session
            .query(func.sum(TaskInstance.pool_slots))
            .filter(TaskInstance.pool == self.pool)
            .filter(TaskInstance.state == State.RUNNING)
            .scalar()
        ) or 0 
开发者ID:apache,项目名称:airflow,代码行数:18,代码来源:pool.py

示例9: ensure_finished_tasks

# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import Session [as 别名]
def ensure_finished_tasks(self, dag, execution_date: pendulum.DateTime, session: Session):
        """
        This method makes sure finished_tasks is populated if it's currently None.
        This is for the strange feature of running tasks without dag_run.

        :param dag: The DAG for which to find finished tasks
        :type dag: airflow.models.DAG
        :param execution_date: The execution_date to look for
        :param session: Database session to use
        :return: A list of all the finished tasks of this DAG and execution_date
        :rtype: list[airflow.models.TaskInstance]
        """
        if self.finished_tasks is None:
            self.finished_tasks = dag.get_task_instances(
                start_date=execution_date,
                end_date=execution_date,
                state=State.finished() + [State.UPSTREAM_FAILED],
                session=session,
            )
        return self.finished_tasks 
开发者ID:apache,项目名称:airflow,代码行数:22,代码来源:dep_context.py

示例10: create_session

# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import Session [as 别名]
def create_session(self):
        """
        Open transaction session with an active database object.
        
        If an error occurs during the session, roll back uncommitted changes
        and report error to log file and user.
        
        If session is no longer needed, commit remaining transactions before closing it.
        """
        session = Session(self.connection)
        logger.info("Create session {0} with {1}".format(
            id(session), self._public_db_uri(str(self.engine.url))))
        try:
            yield session
            session.commit()
            logger.info("Committing remaining transactions to database")
        except Exception as ex:
            session.rollback()
            logger.exception("Database transactions rolled back")
            raise ex
        finally:
            logger.info("Session {0} with {1} closed".format(
                id(session), self._public_db_uri(str(self.engine.url))))
            session.close() 
开发者ID:soccermetrics,项目名称:marcotti,代码行数:26,代码来源:base.py

示例11: get

# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import Session [as 别名]
def get(cls, url: str, session: Session=db.session):
        get_node = Node.query.filter_by(url=url).first
        node = get_node()
        if node:
            return node
        elif get(f'{url}/ping').text == 'pong':
            node = Node(url=url, last_connected_at=datetime.datetime.utcnow())
            if session:
                session.add(node)
                try:
                    session.commit()
                except IntegrityError:
                    node = get_node()
                    if node is None:
                        raise
                    return node
            return node
        else:
            return None 
开发者ID:nekoyume,项目名称:nekoyume,代码行数:21,代码来源:node.py

示例12: test_prevent_hack_and_slash_when_dead

# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import Session [as 别名]
def test_prevent_hack_and_slash_when_dead(
        fx_test_client: FlaskClient, fx_session: Session, fx_user: User,
        fx_private_key: PrivateKey, fx_novice_status: typing.Dict[str, str],
):
    move = fx_user.create_novice(fx_novice_status)
    Block.create(fx_user, [move])

    assert fx_user.avatar().dead is False
    while fx_user.avatar().hp > 0:
        move = fx_user.hack_and_slash()
        Block.create(fx_user, [move])
    assert fx_user.avatar().dead is True

    response = fx_test_client.post('/session_moves', data={
        'name': 'hack_and_slash'
    })
    assert response.status_code == 302 
开发者ID:nekoyume,项目名称:nekoyume,代码行数:19,代码来源:game_test.py

示例13: test_broadcast_node

# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import Session [as 别名]
def test_broadcast_node(
        fx_server: WSGIServer,
        fx_session: scoped_session,
        fx_other_server: WSGIServer,
        fx_other_session: Session,
):
    now = datetime.datetime.utcnow()
    node = Node(url=fx_server.url,
                last_connected_at=now)
    node2 = Node(url=fx_other_server.url,
                 last_connected_at=datetime.datetime.utcnow())
    fx_session.add(node)
    fx_session.commit()
    fx_other_session.add(node2)
    fx_other_session.commit()
    assert not fx_session.query(Node).filter(Node.url == node2.url).first()
    multicast(serialized={'url': fx_other_server.url},
              broadcast=broadcast_node)
    assert fx_session.query(Node).filter(Node.url == node2.url).first()
    assert node.last_connected_at > now 
开发者ID:nekoyume,项目名称:nekoyume,代码行数:22,代码来源:broadcast_test.py

示例14: broadcast_node_failed

# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import Session [as 别名]
def broadcast_node_failed(fx_session: scoped_session,
                          fx_other_session: Session, error):
    now = datetime.datetime.utcnow()
    node = Node(url='http://test.neko',
                last_connected_at=now)
    node2 = Node(url='http://other.neko',
                 last_connected_at=datetime.datetime.utcnow())
    fx_session.add(node)
    fx_session.commit()
    fx_other_session.add(node2)
    fx_other_session.commit()
    assert not fx_session.query(Node).filter(Node.url == node2.url).first()
    with Mocker() as m:
        m.post('http://test.neko', exc=error)
        multicast(serialized={'url': fx_other_server.url},
                  broadcast=broadcast_node)
    assert not fx_session.query(Node).filter(Node.url == node2.url).first()
    assert node.last_connected_at == now 
开发者ID:nekoyume,项目名称:nekoyume,代码行数:20,代码来源:broadcast_test.py

示例15: test_broadcast_move

# 需要导入模块: from sqlalchemy.orm import session [as 别名]
# 或者: from sqlalchemy.orm.session import Session [as 别名]
def test_broadcast_move(
        fx_server: WSGIServer,
        fx_session: scoped_session,
        fx_other_server: WSGIServer,
        fx_other_session: Session,
        fx_user: User,
        fx_novice_status: typing.Mapping[str, str],
):
    now = datetime.datetime.utcnow()
    node = Node(url=fx_server.url,
                last_connected_at=now)
    node2 = Node(url=fx_other_server.url,
                 last_connected_at=datetime.datetime.utcnow())
    move = fx_user.create_novice(fx_novice_status)
    fx_session.add_all([node, node2, move])
    fx_session.commit()
    assert not fx_other_session.query(Move).get(move.id)
    serialized = move.serialize(
        use_bencode=False,
        include_signature=True,
        include_id=True,
    )
    multicast(serialized=serialized, broadcast=broadcast_move)
    assert fx_other_session.query(Move).get(move.id)
    assert node.last_connected_at > now 
开发者ID:nekoyume,项目名称:nekoyume,代码行数:27,代码来源:broadcast_test.py


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