當前位置: 首頁>>代碼示例>>Python>>正文


Python sqlalchemy.orm方法代碼示例

本文整理匯總了Python中sqlalchemy.orm方法的典型用法代碼示例。如果您正苦於以下問題:Python sqlalchemy.orm方法的具體用法?Python sqlalchemy.orm怎麽用?Python sqlalchemy.orm使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在sqlalchemy的用法示例。


在下文中一共展示了sqlalchemy.orm方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: find_ssh_key

# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import orm [as 別名]
def find_ssh_key(session, search_key, username):
    """ Finds and returns SSHKey matching the requested search_key.

    Args:
        session: database session
        search_key (string): The SSH fingerprint we are requested to look up
        username (string or None): If this is provided, the key is looked up
            to belong to the requested user.
    """
    query = session.query(model.SSHKey).filter(
        model.SSHKey.ssh_search_key == search_key
    )

    if username:
        userowner = (
            session.query(model.User.id)
            .filter(model.User.user == username)
            .subquery()
        )
        query = query.filter(model.SSHKey.user_id == userowner)

    try:
        return query.one()
    except sqlalchemy.orm.exc.NoResultFound:
        return None 
開發者ID:Pagure,項目名稱:pagure,代碼行數:27,代碼來源:query.py

示例2: link_pr_issue

# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import orm [as 別名]
def link_pr_issue(session, issue, request, origin="commit"):
    """ Associate the specified issue with the specified pull-requets.

    :arg session: The SQLAlchemy session to use
    :type session: sqlalchemy.orm.session.Session
    :arg issue: The issue mentioned in the commits of the pull-requests to
        be associated with
    :type issue: pagure.lib.model.Issue
    :arg request: A pull-request to associate the specified issue with
    :type request: pagure.lib.model.PullRequest

    """

    associated_issues = [iss.uid for iss in request.related_issues]
    if issue.uid not in associated_issues:
        obj = model.PrToIssue(
            pull_request_uid=request.uid, issue_uid=issue.uid, origin=origin
        )
        session.add(obj)
        session.flush() 
開發者ID:Pagure,項目名稱:pagure,代碼行數:22,代碼來源:query.py

示例3: del_rse

# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import orm [as 別名]
def del_rse(rse_id, session=None):
    """
    Disable a rse with the given rse id.

    :param rse_id: the rse id.
    :param session: The database session in use.
    """

    old_rse = None
    try:
        old_rse = session.query(models.RSE).filter_by(id=rse_id, deleted=False).one()
        if not rse_is_empty(rse_id=rse_id, session=session):
            raise exception.RSEOperationNotSupported('RSE \'%s\' is not empty' % get_rse_name(rse_id=rse_id, session=session))
    except sqlalchemy.orm.exc.NoResultFound:
        raise exception.RSENotFound('RSE with id \'%s\' cannot be found' % rse_id)
    rse = old_rse.rse
    old_rse.delete(session=session)
    try:
        del_rse_attribute(rse_id=rse_id, key=rse, session=session)
    except exception.RSEAttributeNotFound:
        pass 
開發者ID:rucio,項目名稱:rucio,代碼行數:23,代碼來源:rse.py

示例4: restore_rse

# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import orm [as 別名]
def restore_rse(rse_id, session=None):
    """
    Restore a rse with the given rse id.

    :param rse_id: the rse id.
    :param session: The database session in use.
    """

    old_rse = None
    try:
        old_rse = session.query(models.RSE).filter_by(id=rse_id, deleted=True).one()
    except sqlalchemy.orm.exc.NoResultFound:
        raise exception.RSENotFound('RSE with id \'%s\' cannot be found' % rse_id)
    old_rse.deleted = False
    old_rse.deleted_at = None
    old_rse.save(session=session)
    rse = old_rse.rse
    add_rse_attribute(rse_id=rse_id, key=rse, value=True, session=session) 
開發者ID:rucio,項目名稱:rucio,代碼行數:20,代碼來源:rse.py

示例5: get_rse

# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import orm [as 別名]
def get_rse(rse_id, session=None):
    """
    Get a RSE or raise if it does not exist.

    :param rse_id:  The rse id.
    :param session: The database session in use.

    :raises RSENotFound: If referred RSE was not found in the database.
    """

    false_value = False  # To make pep8 checker happy ...
    try:
        tmp = session.query(models.RSE).\
            filter(sqlalchemy.and_(models.RSE.deleted == false_value,
                                   models.RSE.id == rse_id))\
            .one()
        tmp['type'] = tmp.rse_type
        return tmp
    except sqlalchemy.orm.exc.NoResultFound:
        raise exception.RSENotFound('RSE with id \'%s\' cannot be found' % rse_id) 
開發者ID:rucio,項目名稱:rucio,代碼行數:22,代碼來源:rse.py

示例6: reflect_hints_db

# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import orm [as 別名]
def reflect_hints_db(db_path):
    """
    Reflect the database schema of the hints database, automapping the existing tables

    The NullPool is used to avoid concurrency issues with luigi. Using this activates pooling, but since sqlite doesn't
    really support pooling, what effectively happens is just that it locks the database and the other connections wait.

    :param db_path: path to hints sqlite database
    :return: sqlalchemy.MetaData object, sqlalchemy.orm.Session object
    """
    engine = sqlalchemy.create_engine('sqlite:///{}'.format(db_path), poolclass=NullPool)
    metadata = sqlalchemy.MetaData()
    metadata.reflect(bind=engine)
    Base = automap_base(metadata=metadata)
    Base.prepare()
    speciesnames = Base.classes.speciesnames
    seqnames = Base.classes.seqnames
    hints = Base.classes.hints
    featuretypes = Base.classes.featuretypes
    Session = sessionmaker(bind=engine)
    session = Session()
    return speciesnames, seqnames, hints, featuretypes, session 
開發者ID:ComparativeGenomicsToolkit,項目名稱:Comparative-Annotation-Toolkit,代碼行數:24,代碼來源:hintsDatabaseInterface.py

示例7: query_singleton_edges_from_network

# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import orm [as 別名]
def query_singleton_edges_from_network(self, network: Network) -> sqlalchemy.orm.query.Query:
        """Return a query selecting all edge ids that only belong to the given network."""
        ne1 = aliased(network_edge, name='ne1')
        ne2 = aliased(network_edge, name='ne2')
        singleton_edge_ids_for_network = (
            self.session
                .query(ne1.c.edge_id)
                .outerjoin(
                    ne2, and_(
                        ne1.c.edge_id == ne2.c.edge_id,
                        ne1.c.network_id != ne2.c.network_id,
                    ),
                )
                .filter(  # noqa: E131
                    and_(
                        ne1.c.network_id == network.id,
                        ne2.c.edge_id == None,  # noqa: E711
                    ),
                )
        )
        return singleton_edge_ids_for_network 
開發者ID:pybel,項目名稱:pybel,代碼行數:23,代碼來源:cache_manager.py

示例8: setup_class

# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import orm [as 別名]
def setup_class(cls):
        if not tests.is_datastore_supported():
            raise nose.SkipTest("Datastore not supported")
        p.load('datastore')
        ctd.CreateTestData.create()
        cls.sysadmin_user = model.User.get('testsysadmin')
        cls.normal_user = model.User.get('annafan')
        resource = model.Package.get('annakarenina').resources[0]
        cls.data = {
            'resource_id': resource.id,
            'aliases': u'b\xfck2',
            'fields': [{'id': 'book', 'type': 'text'},
                       {'id': 'author', 'type': 'text'},
                       {'id': 'rating with %', 'type': 'text'}],
            'records': [{'book': 'annakarenina', 'author': 'tolstoy',
                         'rating with %': '90%'},
                        {'book': 'warandpeace', 'author': 'tolstoy',
                         'rating with %': '42%'}]
        }

        engine = db._get_engine(
            {'connection_url': config['ckan.datastore.write_url']})
        cls.Session = orm.scoped_session(orm.sessionmaker(bind=engine))
        set_url_type(
            model.Package.get('annakarenina').resources, cls.sysadmin_user) 
開發者ID:italia,項目名稱:daf-recipes,代碼行數:27,代碼來源:test_delete.py

示例9: drop_database

# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import orm [as 別名]
def drop_database(url):
    url = copy(sqlalchemy.engine.url.make_url(url))
    database = url.database
    if url.drivername.startswith('postgresql'):
        url.database = 'postgres'
    elif not url.drivername.startswith('sqlite'):
        url.database = None

    engine = sqlalchemy.create_engine(url)
    if engine.dialect.name == 'sqlite' and url.database != ':memory:':
        os.remove(url.database)
    else:
        text = 'DROP DATABASE {0}'.format(orm.quote(engine, database))
        cnx = engine.connect()
        cnx.execute("ROLLBACK")
        cnx.execute(text)
        cnx.execute("commit")
        cnx.close() 
開發者ID:AnyBlok,項目名稱:AnyBlok,代碼行數:20,代碼來源:testing.py

示例10: _setup_retry_tracker_table

# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import orm [as 別名]
def _setup_retry_tracker_table(self):
        metadata = sqlalchemy.MetaData()
        self.retry_table = sqlalchemy.Table(
            'retry_tracker', metadata,
            sqlalchemy.Column(
                'id', sqlalchemy.Integer,
                autoincrement=True,
                primary_key=True,
            ),
        )
        metadata.create_all(self.engine)
        self.addCleanup(metadata.drop_all, self.engine)

        class RetryTracker(object):
            pass

        sqlalchemy.orm.mapper(RetryTracker, self.retry_table)
        self.retry_tracker = RetryTracker 
開發者ID:openstack,項目名稱:networking-odl,代碼行數:20,代碼來源:test_base_db.py

示例11: single_item_query

# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import orm [as 別名]
def single_item_query(self, loadonly=None):
        """A query representing the single item referenced by the request.

        **URL (matchdict) Parameters**

            **id** (*str*): resource id

        Returns:
            sqlalchemy.orm.query.Query: query which will fetch item with id
            'id'.
        """
        if not loadonly:
            loadonly = self.allowed_requested_query_columns.keys()
        return self.dbsession.query(
            self.model
        ).options(
            load_only(*loadonly)
        ).filter(
            self.id_col(self.model) == self.obj_id
        ) 
開發者ID:colinhiggs,項目名稱:pyramid-jsonapi,代碼行數:22,代碼來源:collection_view.py

示例12: related_limit

# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import orm [as 別名]
def related_limit(self, relationship):
        """Paging limit for related resources.

        **Query Parameters**

            **page[limit:relationships:<relname>]:** number of results to
            return per page for related resource <relname>.

        Parameters:
            relationship(sqlalchemy.orm.relationships.RelationshipProperty):
                the relationship to get the limit for.

        Returns:
            int: paging limit for related resources.
        """
        limit_comps = ['limit', 'relationships', relationship.obj.key]
        limit = self.default_limit
        qinfo = self.collection_query_info(self.request)
        while limit_comps:
            if '.'.join(limit_comps) in qinfo['_page']:
                limit = int(qinfo['_page']['.'.join(limit_comps)])
                break
            limit_comps.pop()
        return min(limit, self.max_limit) 
開發者ID:colinhiggs,項目名稱:pyramid-jsonapi,代碼行數:26,代碼來源:collection_view.py

示例13: invalidate

# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import orm [as 別名]
def invalidate(cache, session, earliest, latest):
        """Invalidates/deletes all cached responses in the given interval to
        ensure these data is generated anew. This is meant to be run when the
        underlying data for this interval changes, for instance since new data
        has been imported.

        :param session: SQLAlchemy Session
        :type session: sqlalchemy.orm.session.Session
        :param earliest: Earliest time of the interval to invalidate
        :type earliest: datetime.datetime
        :param latest: Latest time of the interval to invalidate
        :type latest: datetime.datetime

        """
        logger.debug('Invalidating cache in interval %s..%s',
                     earliest.isoformat(), latest.isoformat())
        session.query(cache)\
               .filter(and_(or_(cache.begin.is_(None),
                                cache.begin <= latest),
                            or_(cache.end.is_(None),
                                cache.end > earliest)))\
               .delete()
        session.commit() 
開發者ID:emissions-api,項目名稱:emissions-api,代碼行數:25,代碼來源:db.py

示例14: get_session

# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import orm [as 別名]
def get_session():
    """Get a new session.

    Lazy load the database connection and create the tables.

    Returns:
        sqlalchemy.orm.session.Session -- SQLAlchemy Session object
    """
    global __session__
    # Create database connection, tables and Sessionmaker if neccessary.
    if not __session__:
        Engine = create_engine(
            database, echo=logger.getEffectiveLevel() == logging.DEBUG)
        __session__ = sessionmaker(bind=Engine)
        Base.metadata.create_all(Engine)

    # Return new session object
    return __session__() 
開發者ID:emissions-api,項目名稱:emissions-api,代碼行數:20,代碼來源:db.py

示例15: insert_dataset

# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import orm [as 別名]
def insert_dataset(session, data, tbl):
    '''Batch insert data into the database using PostGIS specific functions.

    :param session: SQLAlchemy Session
    :type session: sqlalchemy.orm.session.Session
    :param data: DataFrame containing value, timestamp, longitude and latitude
    :type data: pandas.core.frame.DataFrame
    :param tbl: Base class representing the database table for the data
    :type tbl: sqlalchemy.ext.declarative.api.DeclarativeMeta
    '''
    values = sqlalchemy.select([sqlalchemy.func.unnest(data.value),
                                sqlalchemy.func.unnest(data.timestamp),
                                sqlalchemy.func.ST_MakePoint(
                                    sqlalchemy.func.unnest(data.longitude),
                                    sqlalchemy.func.unnest(data.latitude))])
    query = sqlalchemy.insert(tbl).from_select(tbl.columns, values)
    session.execute(query) 
開發者ID:emissions-api,項目名稱:emissions-api,代碼行數:19,代碼來源:db.py


注:本文中的sqlalchemy.orm方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。