Example #1
0
def app():
    app = create_app(ConfigTest)
    with app.app_context():
        db.create_all()
        yield app
        db.session.remove()
        db.drop_all()
Example #2
0
def populate_db():
    # Reset database tables
    db.drop_all()
    db.create_all()

    # Get list of subreddits
    with open("app/db/subreddits.json") as f:
        data = json.load(f)
        SUBREDDITS_LIST = data["subreddits"]
        f.close()

    # Process data for each subreddit
    for subreddit in SUBREDDITS_LIST:
        sr_valid, sr_description, sr_subscribers = get_subreddit_info(
            subreddit)
        # If invalid/inappropriate subreddit, skip processing information
        if not sr_valid:
            continue

        fetched_data = fetch_data(subreddit)
        word_to_index, processed_data, post_arr = process_data(fetched_data)
        word_arr = generate_strings(word_to_index, processed_data)
        db.session.add(
            Metadata(subreddit, sr_description, sr_subscribers, post_arr))
        db.session.add(Data(subreddit, word_arr))
        db.session.commit()
def create_app(env="DEFAULT"):
    app = Flask(__name__)
    app.config.from_object(get_config(env))

    app.register_blueprint(auth_bp)
    app.register_blueprint(shops_bp)
    app.register_blueprint(products_bp)

    db.init_app(app)
    login.init_app(app)
    db.drop_all(app=app)

    migrate.init_app(app, db)

    with app.app_context():
        db.create_all()
        """Some default data"""
        db.session.add(user_1)
        db.session.add(user_2)
        db.session.add(shop_1)
        db.session.add(shop_2)
        db.session.add(category_1)
        db.session.add(category_2)
        db.session.add(product_1)
        db.session.add(product_2)
        shop_1.products.append(product_2)
        db.session.commit()

    return app
Example #4
0
def db(app):
    _db.init_app(app)
    with app.app_context():
        _db.drop_all()
        _db.create_all()
        print('cleaned the db for a new test case')

        yield _db
        _db.drop_all()
Example #5
0
    def setUp(self):
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
        db.drop_all()
        init_db()

        self.driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true', '--ssl-protocol=any'])
        self.url = 'http://127.0.0.1:5000'
        self.email = "*****@*****.**"
        self.password = "******"
        self.username = "******"
Example #6
0
 def run(self):
     if (input(
             "Are you sure you want to drop all tables and recreate? (y/N)\n"
     ).lower() == "y"):
         print("Dropping tables...")
         db.drop_all()
         db.create_all()
         seed_general()
         db.session.commit()
         print("DB successfully seeded.")
Example #7
0
def test_db(app):
    create_db(app)

    db.init_app(app)
    connect_to_db(app)

    db.create_all()
    load_test_data()

    yield db

    # cleanup
    db.session.close()
    db.drop_all()
Example #8
0
    def tearDown(self):
        db.session.remove()
        db.drop_all()

        self.app_context.pop()
Example #9
0
 def tearDown(self):
     db.session.remove()
     db.drop_all()
     self.app_context.pop()
Example #10
0
 def get(self):
     db.drop_all()
     db.create_all()
     return {
         'message': 'Database recreated.',
     }
def init_app(database):

    #importtaa oracle tarvittaessa
    if database == "oracle":
        import cx_Oracle  #siirretty oracle importit tänne, koska pytest ei tykkää niistä tuolla ylhäällä
        import app.oracleConfig

    #määritä app
    app = Flask(__name__, static_folder='../build', static_url_path='/')
    cors = CORS(app)

    #kirjautuminen
    app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(minutes=30)
    app.config["SESSION_REFRESH_EACH_REQUEST"] = True
    if database == "oracle":
        login_manager = LoginManager()
        login_manager.init_app(app)
        app.config["SECRET_KEY"] = urandom(32)
        app.config['LOGIN_DISABLED'] = False
    else:
        login_manager = LoginManager()
        login_manager.init_app(app)
        app.config["SECRET_KEY"] = urandom(32)
        app.config['LOGIN_DISABLED'] = True

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    #Kayttajaroolit (alustava, kopioitu vanhasta projektista)
    # from functools import wraps
    # def login_required(_func=None, *, role="ANY"):
    #     def wrapper(func):
    #         @wraps(func)
    #         def decorated_view(*args, **kwargs):
    #             if not (current_user and current_user.is_authenticated):
    #                 return login_manager.unauthorized()

    #             acceptable_roles = set(("ANY", current_user.getRole()))

    #             if role not in acceptable_roles:
    #                 return login_manager.unauthorized()

    #             return func(*args, **kwargs)
    #         return decorated_view
    #     return wrapper if _func is None else wrapper(_func)

    #määrittele tietokantayhteys
    if database == "oracle":
        dnsStr = cx_Oracle.makedsn('oracle.luomus.fi',
                                   1521,
                                   service_name='oracle.luomus.fi')
        dnsStr = dnsStr.replace('SID', 'SERVICE_TYPE')
        try:
            app.config[
                "SQLALCHEMY_DATABASE_URI"] = "oracle://" + oracleConfig.username + ":" + oracleConfig.password + "@" + dnsStr
            app.config["SQLALCHEMY_ECHO"] = True
            print('Tietokantayhteys luotu.')
        except Exception as e:
            print(e)
    else:
        try:
            app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///:memory:'
            app.config["SQLALCHEMY_ECHO"] = True
            print('Testitietokantayhteys luotu.')
        except Exception as e:
            print(e)

    #Tietokannan luonti
    app.register_blueprint(api_blueprint)
    db.init_app(
        app
    )  #db siirretty omaksi luokaksi, että se näkyy kaikille, jostain syystä init_app() systeemillä tehtäessä se ei näy. kaikkiin models.py tiedostoihin from app.db import db

    with app.app_context(
    ):  #appioliota käyttäen luodaan tietokantataulut, tämä googlesta
        try:

            #Määritellään tyhjennetäänkö tietokanta sovelluksen alussa
            if database == "oracle":
                #db.reflect()
                #db.drop_all()
                db.create_all()
            else:
                db.reflect()
                db.drop_all()
                db.create_all()
            print('Taulut luotu')

            #Lisätään tiedot tiedostosta
            SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
            filename = os.path.join(SITE_ROOT, '', 'locations.json')
            with open(filename) as json_file:
                data = json.load(json_file)
                for o in data["observatories"]:
                    createObservatory(o['observatory'])
                    obsId = getObservatoryId(o['observatory'])
                    for l in o["locations"]:
                        createLocation(l, obsId)
                    for t in o["types"]:
                        createType(t, obsId)

            print('Lintuasema luotu')

        except Exception as e:
            print(e)

    return app
Example #12
0
import sys
from app import app

if __name__ == "__main__":
    if( len( sys.argv ) >= 2 ):
        if( sys.argv[1] == "create_db" ):
            print( "Creating the database." )
            from app.db import db
            from app.models.account import *
            from app.models.car import *
            from app.models.driver import *
            from app.models.request import *
            from app.models.rider import *
            from app.models.schedule import *
            from app.models.location import *
            from app.models.route import *
            db.drop_all()
            db.create_all()
            db.create_default_roles()
        elif( sys.argv[1] == "create_data" ):
            db.create_some_example_data()
    else:
        app.run( debug=True )
Example #13
0
def drop_tables():
    """Drop database tables and wipe data."""
    if prompt_bool('Confirm delete all data?'):
        db.drop_all()
Example #14
0
 def tearDown(self):
     db.session.remove()
     db.drop_all()
 def tearDown(self):
     db.session.commit()
     db.session.close_all()
     db.drop_all()
Example #16
0
 def teardown():
     _db.drop_all()
Example #17
0
def tearDownDB(self):
    with self.app.app_context():
        db.session.remove()
        db.drop_all()
Example #18
0
def test_db(setup_db):
    db.create_all()
    yield
    db.drop_all()
Example #19
0
    def run(self):
        db.drop_all()
        print(f" - database dropped")

        db.create_all()
        print(f" - database created")
Example #20
0
 def tearDown(self):
     db.session.remove()
     db.drop_all()
     self.driver.close()
Example #21
0
def teardown():
    """
    Removes the database session after each testrun and clears the database.
    """
    db.drop_all()
    dbs.remove()
Example #22
0
 def pop():
     db.drop_all()
Example #23
0
 def setUp(self):
     app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
     # For most tests we don't care about the CSRF token.
     flask_wtf.csrf.validate_csrf = lambda token: True
     db.drop_all()
     init_db()
def tearDownDB(self):
    with self.app.app_context():
        db.session.remove()
        db.drop_all()
Example #25
0
def create_tables():
    db.drop_all()
    db.create_all()
    print('tables has been created')
Example #26
0
 def teardown():
     _db.session.commit()
     _db.drop_all()
Example #27
0
 def tearDown(self):
     db.session.remove()
     db.drop_all()