def test_delete():
    u = User(nickname='john', email='*****@*****.**')
    p = Post(body='test', author=u, timestamp=datetime.utcnow())
    db.session.add(u)
    db.session.add(p)
    db.session.commit()
    p = Post.query.get(1)
    db.session.remove()
    db.session = db.create_scoped_session()
    db.session.delete(p)
    db.session.commit()
Exemple #2
0
    def scrap_recent_articles():

        tags = [
            'look',
            'money',
            'friends',
            'health',
            'relations',
            'rabota',
            'other',
            'parents',
            'sex',
            'family',
            'tech',
            'stud'
        ]
        urls = ['http://killpls.me/bytag/%s' % tag for tag in tags]
        urls.append('http://killpls.me')

        for url in urls:

            print 'loading %s...' % url

            count = 0
            current_page = None
            page_path = '/page' if url == urls[-1] else ''

            while count < cfg.ARTICLES_COUNT_MAX:

                paged_url = url

                if current_page:
                    current_page -= 1
                    paged_url += '%s/%d' % (page_path, current_page)

                print ' loading %s...' % paged_url

                with closing(urllib.urlopen(paged_url)) as request:
                    xml_data = BeautifulSoup.BeautifulSoup(request.read())

                articles_container = xml_data.findAll('div', attrs={'id': 'stories'})
                articles_content = [item for item in articles_container[0].contents[5:-9] if type(item) == BeautifulSoup.Tag]

                if not current_page:
                    current_page = int(articles_content[0].div.div.span.text)

                session = db.create_scoped_session()

                count += Article.parse_articles_content(session, articles_content[4:])

                session.commit()
                session.close()

                print '  loaded %d' % count
Exemple #3
0
 def test_delete_post(self):
     u = User(nickname='john', email='*****@*****.**')
     p = Post(body='test post', author=u, timestamp=datetime.utcnow())
     db.session.add(u)
     db.session.add(p)
     db.session.commit()
     # query the post and destroy the session
     p = Post.query.get(1)
     db.session.remove()
     # delete the post using a new session
     db.session = db.create_scoped_session()
     db.session.delete(p)
     db.session.commit()
Exemple #4
0
 def test_delete_post(self):
     # create a user and a post
     ##datetime
     u = User(nickname='john', email='*****@*****.**')
     p = Post(body='test post', author=u, timestamp=datetime.utcnow())
     db.session.add(u)
     db.session.add(p)
     db.session.commit()
     # query the post and destroy the session
     p = Post.query.get(1)
     db.session.remove()
     # delete the post using a new session
     db.session = db.create_scoped_session()
     db.session.delete(p)
     db.session.commit()
def session(db, request):
    """Creates a new database session for a test."""
    connection = db.engine.connect()
    transaction = connection.begin()

    options = dict(bind=connection, binds={})
    session = db.create_scoped_session(options=options)

    db.session = session

    def teardown():
        transaction.rollback()
        connection.close()
        session.remove()

    request.addfinalizer(teardown)
    return session
def session(db, request):
    """Creates a new database session for a test."""
    connection = db.engine.connect()
    transaction = connection.begin()

    options = dict(bind=connection, binds={})
    session = db.create_scoped_session(options=options)

    db.session = session

    def teardown():
        transaction.rollback()
        connection.close()
        session.remove()

    request.addfinalizer(teardown)
    return session
Exemple #7
0
def session(app, db, request):
    """
    Returns function scoped session.
    """
    with app.app_context():
        conn = db_instance.engine.connect()
        txn = conn.begin()

        options = dict(bind=conn, binds={})
        sess = db_instance.create_scoped_session(options=options)

        db_instance.session = sess
        yield sess

        sess.remove()

        # This instructions rolls back any commits that were executed in the tests.
        txn.rollback()
def db(app, request):
    def teardown():
        _db.drop_all()

    _db.app = app
    _db.create_all()

    connection = _db.engine.connect()
    transaction = connection.begin()
    options = dict(bind=connection, binds={})
    session = _db.create_scoped_session(options=options)
    db.session = session

    populate_test_db(session)

    transaction.rollback()
    connection.close()
    session.remove()

    request.addfinalizer(teardown)
    return _db
Exemple #9
0
def populate_colors_in_db():
    session = database.create_scoped_session()
    colors = session.query(Color)
    for color in colors:
        if color.hex:
            continue
        else:
            color_obj = get_color(color.captured_text)

            original_rgb_vals = [float(item) for item in color_obj["rgb"]]

            color.rgb = [int(item) for item in original_rgb_vals]
            color.lab = [float(item) for item in color_obj["lab"]]
            print("color lab", color.lab)
            color.hex = color_obj["hex"][1:]
            color.lum = lum(*original_rgb_vals)
            color.hsv = list(colorsys.rgb_to_hsv(*color.rgb))
            session.merge(color)
            session.flush()
            session.commit()
            print("added", color.id)
Exemple #10
0
    def test_after_commit_hooks_are_specific_to_a_session(
        self, user_subscribed, session, app
    ):

        # What does this test prove? Well - we start by showing
        # the thing works and by setting up a an "after_commit" hook
        # on the session.  (There SHOULD BE one session per request.)
        # The next request should NOT fire the "after_commit" hook
        # because it has a new session.  IE - we are not leaking
        # Model instances across requests, and not firing subscribe
        # events for instances we didn't change

        free_user = UserFactory(tier="free")

        UserUpdate(
            user=free_user,
            rels={"plan": {"data": {"type": "plan", "id": str(Plan.paid().id)}}},
        ).update()

        session.commit()
        session.expire_all()

        user_subscribed.assert_called_with(free_user.id, Plan.paid().id)
        user_subscribed.reset_mock()

        sess = db.create_scoped_session()

        free_user2 = UserFactory(tier="free", email="*****@*****.**")

        UserUpdate(
            user=free_user2,
            rels={"plan": {"data": {"type": "plan", "id": str(Plan.free().id)}}},
        ).update()

        session.commit()

        user_subscribed.assert_not_called()

        sess.remove()
Exemple #11
0
    def _setup_nested_txn(self):

        # connect to the database
        self.connection = db.engine.connect()

        # begin a non-ORM transaction
        self.transaction = self.connection.begin()

        options = dict(bind=self.connection, binds={})
        self.session = db.create_scoped_session(options=options)

        db.session = self.session

        # then each time that SAVEPOINT ends, reopen it
        @event.listens_for(self.session, "after_transaction_end")
        def restart_savepoint(session, transaction):
            if transaction.nested and not transaction._parent.nested:
                # ensure that state is expired the way
                # session.commit() at the top level normally does
                # (optional step)
                session.expire_all()

                session.begin_nested()
Exemple #12
0
def session(app, db, request):
    """
    Returns function-scoped session.
    """
    with app.app_context():
        conn = _db.engine.connect()
        txn = conn.begin()

        options = dict(bind=conn, binds={})
        sess = _db.create_scoped_session(options=options)

        # establish  a SAVEPOINT just before beginning the test
        # (http://docs.sqlalchemy.org/en/latest/orm/session_transaction.html#using-savepoint)
        sess.begin_nested()

        @event.listens_for(sess(), 'after_transaction_end')
        def restart_savepoint(sess2, trans):
            # Detecting whether this is indeed the nested transaction of the test
            if trans.nested and not trans._parent.nested:
                # The test should have normally called session.commit(),
                # but to be safe we explicitly expire the session
                sess2.expire_all()
                sess.begin_nested()

        _db.session = sess
        # Extend session to all factories
        for factory in factories:
            factory._meta.sqlalchemy_session = sess

        yield sess

        # Cleanup
        sess.remove()
        # This instruction rollsback any commit that were executed in the tests.
        txn.rollback()
        conn.close()
Exemple #13
0
def populate_colors_in_db():
    print("Adding color data...")
    session = database.create_scoped_session()
    colors = session.query(Color)
    work_parallel(add_color_data, colors)
Exemple #14
0
def get_session():
    # return db.create_session(options={})
    return db.create_scoped_session(options={
        'autocommit': True,
        'autoflush': False
    })
Exemple #15
0
def _getSession():
    return db.create_scoped_session()
Exemple #16
0
def get_db_session():
    return db.create_scoped_session()