本文整理匯總了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
示例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
示例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
)
示例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)
示例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()
示例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
示例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
示例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
示例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
示例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()
示例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
示例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
示例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
示例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
示例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