How to use the sqlalchemy.orm.sessionmaker function in SQLAlchemy

To help you get started, we’ve selected a few SQLAlchemy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ReliaQualAssociates / ramstk / tests / dao / programdb / _test_ramstkincidentaction.py View on Github external
def setUp(self):
        """
        Sets up the test fixture for the RAMSTKIncidentAction class.
        """

        engine = create_engine('sqlite:////tmp/TestDB.ramstk', echo=False)
        session = scoped_session(sessionmaker())

        session.remove()
        session.configure(bind=engine, autoflush=False, expire_on_commit=False)

        self.DUT = session.query(RAMSTKIncidentAction).first()
        self.DUT.action_prescribed = self._attributes[3]

        session.commit()
github geoadmin / mf-chsdi3 / tests / integration / test_layers.py View on Github external
def getSession(self):
        session = scoped_session(sessionmaker())
        yield session
        session.close()
github petl-developers / petl / docs / dbtests.py View on Github external
exercise(dbapi_cursor)
    dbapi_cursor.close()
    
    # exercise sqlalchemy dbapi_connection
    setup_postgresql(dbapi_connection)
    from sqlalchemy import create_engine
    sqlalchemy_engine = create_engine('postgresql+psycopg2://%s:%s@%s/%s' %
                                      (user, passwd, host, db))
    sqlalchemy_connection = sqlalchemy_engine.connect()
    exercise(sqlalchemy_connection)
    sqlalchemy_connection.close()
    
    # exercise sqlalchemy session
    setup_postgresql(dbapi_connection)
    from sqlalchemy.orm import sessionmaker
    Session = sessionmaker(bind=sqlalchemy_engine)
    sqlalchemy_session = Session()
    exercise(sqlalchemy_session)
    sqlalchemy_session.close()

    # other exercises
    exercise_ss_cursor(dbapi_connection,
                       lambda: dbapi_connection.cursor(name='arbitrary'))
    exercise_with_schema(dbapi_connection, 'public')
    exercise_unicode(dbapi_connection)
github AutoOps / MagicStack-Proxy / handlers / account / v1_0 / resource.py View on Github external
def delete_object(obj_name, obj_id):
    msg = 'success'
    Session = sessionmaker()
    Session.configure(bind=engine)
    session = Session()
    del_obj = None
    try:
        if obj_name == 'User':
            del_obj = session.query(User).get(int(obj_id))
        elif obj_name == 'UserGroup':
            del_obj = session.query(UserGroup).get(int(obj_id))
        if del_obj is None:
            raise ValueError(u'对象不存在')
        session.delete(del_obj)
        session.commit()
    except Exception as e:
        logger.error(e)
        msg = 'error'
    finally:
github FreeJournal / freejournal / cache / cache.py View on Github external
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy import MetaData
from db import setup_db, connect_db
from .models.collection import Collection
from .models.document import Document
from .models.collection_version import CollectionVersion
from .models.keyword import Keyword

engine = connect_db()
setup_db(engine)
DBSession = sessionmaker(bind=engine)
meta = MetaData(bind=engine)


class Cache():

    """A Cache is an object used to communicate with the sqlalchemy database and store FreeJournal data locally

       Attributes:
          session: the sqlalchemy session for this Cache
    """

    def __init__(self):
        """Create a new database session to support
           insertion or removal of local data."""
        self.session = DBSession()
github atiaxi / chromabot / bin / export.py View on Github external
def main():
    full = "sqlite:///%s" % realpath(sys.argv[1])
    if len(sys.argv) < 3:
        raise ValueError("Usage: export.py  ")
    engine = create_engine(full)
    sessionfactory = sessionmaker(bind=engine)
    
    session = sessionfactory()
    
    users = session.query(User).all()
    results = [
        { 'id': u.id,
         'name': u.name,
         'team': u.team,
         'loyalists': 300,
         'defectable': True
        } for u in users
    ]
    with open(sys.argv[2], "w") as outfile:
        #j = json.dumps(results)
        json.dump(results, outfile)
github AutoOps / MagicStack-Proxy / handlers / permission / v1_0 / resource.py View on Github external
def save_object(obj_name, param):
    """
    保存数据
    """
    msg = 'success'
    Session = sessionmaker()
    Session.configure(bind=engine)
    session = Session()
    try:
        if obj_name == "PermRole":
            save_permrole(session, param)
        elif obj_name == "PermSudo":
            save_permsudo(session, param)
    except Exception as e:
        logger.error(e)
        msg = 'error'
    finally:
        session.close()
    return msg
github Areizen / Android-Malware-Sandbox / lib / modules / ModuleGeneral.py View on Github external
def url(self, url):
        '''
        Add an url to the database
        :param url:
        :return:
        '''
        logging.debug("ModuleGeneral:url()")

        # Create a thread local session
        engine = Database.get_engine()

        session_factory = sessionmaker(bind=engine)
        Session = scoped_session(session_factory)
        session = Session()
        Session.remove()

        url = Url(url)

        whitelist = ['0.0.0.0', '172.', '216.58.']
        # whitelist = []

        add = True
        if url.ip is not None:
            for i in whitelist:
                if url.ip.startswith(i):
                    add = False

        if add:
github johnbywater / eventsourcing / eventsourcing / infrastructure / sqlalchemy / datastore.py View on Github external
def session(self):
        if self._session is None:
            if self._engine is None:
                self.setup_connection()
            session_factory = sessionmaker(bind=self._engine)
            self._session = scoped_session(session_factory)
        return self._session
github dichotomy / scorebot / SBE-2.5-Old / Database.py View on Github external
class Flag(Base):
    __tablename__ = "flag"
    id = Column(Integer, primary_key=True)
    blueteam_id = Column(Integer, ForeignKey('blueteam.id'))
    name = Column(String)
    points = Column(Integer)
    value = Column(String)
    answer = Column(String)



if __name__=="__main__":
    from sqlalchemy import create_engine
    engine = create_engine('sqlite:///v3_0dbTest.sqlite')
    from sqlalchemy.orm import sessionmaker
    session = sessionmaker()
    session.configure(bind=engine)
    Base.metadata.create_all(engine)
    bt = Blueteam(name="ALPHA", email="alpha@alpha.net", score=0, dns="10.100.101.100")
    s = session()
    s.add(bt)
    print s.query(Blueteam).all()