Esempio n. 1
0
    def setUp(self):
        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()
        self.client = self.app.test_client(use_cookies=True)

        db.create_all()
def create_app(config=DevelopmentConfig):
    app = Flask(__name__)
    migrate = Migrate(app, db)
    csrf = CSRFProtect(app)
    app.config.from_object(config)
    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'

    login_manager.init_app(app)
    db.init_app(app)
    ma.init_app(app)
    csrf.init_app(app)

    with app.app_context():
        db.create_all()

    # register each active blueprint
    for url, blueprint in ACTIVE_ENDPOINTS:
        app.register_blueprint(blueprint, url_prefix=url)

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

    @app.route('/spec')
    def spec():
        swag = swagger(app)
        swag['info']['version'] = "1.0.0"
        swag['info']['title'] = "pygroup-Web"
        swag['info']['description'] = "My shop example using Flask"
        return jsonify(swag)

    app.register_blueprint(swagger_blueprint, url_prefix=SAWGGER_URL)

    return app
Esempio n. 3
0
def db(app, request):
    """
    A fixture to create a test DB for our session and destroy it after
    running the tests

    :param Flask app:
    :param Request request:
    :return SQLAlchemy:
    """
    def teardown():
        _db.session.commit()
        _db.drop_all()

    _db.app = app
    _db.create_all()
    """
    The following will execute an SQL file to insert some fixture data in the database
    to make the tests ready. I don't really like this way of populating data.
    I think it's better to insert fixture data programmatically which is described 
    in yaml / json files.
    """
    with open(os.path.join(app.root_path, 'test/fixtures/test_data.sql')) as f:
        engine = _db.create_engine(app.config.get('SQLALCHEMY_DATABASE_URI'))
        connection = engine.connect()
        connection.execute(text(f.read()))
        connection.close()

    request.addfinalizer(teardown)
    return _db
Esempio n. 4
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()
Esempio n. 5
0
 def create_database():
     db.create_all()
     ProductType.init_data()
     Product.init_data()
     Role.init_data()
     User.init_data()
     OrderStatus.init_data()
Esempio n. 6
0
def create():
    """Creates a new db and builds tables (short-circuiting migrations)"""
    from app.db import db

    new()
    db.create_all()
    local("alembic -c%s stamp head" % config.alembic_ini())
Esempio n. 7
0
def create_app():
    """
    flask application initialization skeleton

    :return Flask:
    """
    app_dir_path = os.path.dirname(os.path.realpath(__file__))
    root_path = os.path.abspath(os.path.join(app_dir_path, os.pardir))
    app = Flask(__name__, instance_relative_config=True, root_path=root_path)

    app.config.from_object(os.getenv('APP_SETTINGS', 'app.config.LocalConfig'))

    if os.path.exists(os.path.join(app.instance_path, 'log_config.conf')):
        fileConfig(os.path.join(app.instance_path, 'log_config.conf'),
                   defaults={
                       'logfilename':
                       os.path.join(app.root_path,
                                    app.config.get('LOGFILE_PATH'))
                   },
                   disable_existing_loggers=False)

    with app.app_context():
        from app.api import api
        from app.db import db
        from app.routes import configure_routes

        configure_routes(api)
        api.init_app(app)
        db.init_app(app)

        db.create_all()

    return app
Esempio n. 8
0
    def init_app(app):
        Config.init_app(app)
        with app.app_context():

            from app.db import db
            from app.models import User
            from app.models import Plan

            db.init_app(app)
            db.create_all()

            # check if plans exist
            if len(Plan.query.all()) != 4:
                p1 = Plan(id=1, name='free', description='All the basic features of SupportService', cost=0)
                db.session.add(p1)
                p2 = Plan(id=2, name='bronze', description='Everything in free and email support.', cost=25)
                db.session.add(p2)
                p3 = Plan(id=3, name='silver', description='Everything in bronze and chat support.', cost=50)
                db.session.add(p3)
                p4 = Plan(id=4, name='gold', description='Everything in silver and 99.999% uptime SLA!', cost=50)
                db.session.add(p4)
                db.session.commit()

            # check if user exists
            if User.query.filter_by(email='*****@*****.**').first() is None:
                app.logger.info("Creating test user: [email protected] password: test")
                u = User(email='*****@*****.**')
                u.set_password('test')
                db.session.add(u)
                db.session.commit()
            else:
                app.logger.info("You can login with user: [email protected] password: test")
Esempio n. 9
0
 def setUp(self):
     env_id = '12345'
     env_api_key = '12345'
     self.app = create_app(env_id, env_api_key, config_name='testing')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
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
Esempio n. 11
0
def client():
    app.config.from_object(TestingConfig())
    db.session.remove()
    drop_everything(db)
    db.create_all()
    client = app.test_client()
    yield client
Esempio n. 12
0
def create():
	app = Flask(__name__)
	app.config.from_object(Config)
	db.init_app(app)
	lm.init_app(app)
	degrade()
	with app.test_request_context():
		db.create_all()
	import app.test as test
	app.register_blueprint(test.module)
	import app.create as create
	app.register_blueprint(create.module)
	import app.login as login
	app.register_blueprint(login.module)
	import app.index as index
	app.register_blueprint(index.module)
	import app.get as get
	app.register_blueprint(get.module)
	import app.add as add
	app.register_blueprint(add.module)
	import app.change as change
	app.register_blueprint(change.module)
	import app.remove as remove
	app.register_blueprint(remove.module)
	import app.post as post
	app.register_blueprint(post.module)
	return app
Esempio n. 13
0
def create_app():
    """
    App factory pattern avoids circular imports, so instead of importing
    'app' directly you import its factory. If you need the current running app
    you can use 'from flask import current_app'
    :return: app
    """
    app = Flask(__name__)
    config_name = os.environ.get('FLASK_CONFIG') or 'development'
    cfg = os.path.join(os.getcwd(), 'config', config_name + '.py')
    app.config.from_pyfile(cfg)

    # initialize extensions
    bootstrap.init_app(app)
    db.init_app(app)

    # import blueprints
    from app.dashboard.views import dashboard_blueprint
    from app.operatingsystem.views import os_blueprint
    from app.project.views import project_blueprint
    from app.release.views import release_blueprint
    from app.testrun.views import run_blueprint

    app.register_blueprint(dashboard_blueprint)
    app.register_blueprint(os_blueprint)
    app.register_blueprint(project_blueprint)
    app.register_blueprint(release_blueprint)
    app.register_blueprint(run_blueprint)

    configure_admin(app, db)

    db.create_all(app=app)

    return app
Esempio n. 14
0
def app():
    app = create_app(ConfigTest)
    with app.app_context():
        db.create_all()
        yield app
        db.session.remove()
        db.drop_all()
Esempio n. 15
0
 def setUp(self):
     #self.app = SubdomainDispatcher('localhost','default')
     env_id = '123456'
     env_api_key = '123456'
     self.app = create_app(env_id, env_api_key, config_name='testing')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
Esempio n. 16
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()
Esempio n. 17
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('config.BaseConfig')
    app.register_blueprint(file_upload_bp)
    app.register_blueprint(bank_marketing_bp)
    db.init_app(app)
    db.app = app
    db.create_all()
    return app
Esempio n. 18
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.")
 def setUp(self):
     #self.app = SubdomainDispatcher('localhost','default')
     env = {
         'LD_CLIENT_KEY': '12345',
         'LD_FRONTEND_KEY': '12345'
     }
     self.app = create_app('testing', env, config_name='testing')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
Esempio n. 20
0
def create_tables():
    db.create_all()
    db.session.commit()
    from app.models.user import UserModel
    if not UserModel.find_by_username("admin"):
        UserModel(username="******",
                  password="******",
                  firstName="admin",
                  lastName="admin",
                  phoneNumber="123467890").save_to_db()
Esempio n. 21
0
def database():
    url = str(DATABASE_URL)

    if database_exists(url):
        drop_database(url)

    create_database(url)

    db.create_all()

    return db
Esempio n. 22
0
def _db(request, app):
    from app.db import db

    db.app = app
    db.create_all()

    @request.addfinalizer
    def pop():
        db.drop_all()

    return db
Esempio n. 23
0
    def init_app(app):
        Config.init_app(app)

        with app.app_context():
            from app.db import db
            from app.models import User

            db.init_app(app)
            db.create_all()

            from ldclient.config import Config as __config
            ldclient.set_config(__config(offline=True))
Esempio n. 24
0
def create_app():
    app = Flask(__name__)
    app.secret_key = "My secret"

    app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///db.sqlite"

    from app.api.person import person_bp
    app.register_blueprint(person_bp)

    db.init_app(app)
    with app.app_context():
        db.create_all()
    return app
Esempio n. 25
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()
Esempio n. 26
0
def db(app, request):
    """Session-wide test database."""

    # if os.path.exists(TESTDB_PATH):
    #     os.unlink(TESTDB_PATH)

    def teardown():
        _db.drop_all()
        # os.unlink(TESTDB_PATH)

    _db.app = app
    _db.create_all()

    request.addfinalizer(teardown)
    return _db
Esempio n. 27
0
def create_app(config=DevelopmentConfig):
    app = Flask(__name__)
    migrate = Migrate(app, db)
    csrf = CSRFProtect(app)
    app.config.from_object(config)
    db.init_app(app)
    ma.init_app(app)
    csrf.init_app(app)

    with app.app_context():  #el contexto es la DB, el serializable
        db.create_all()

    for url, blueprint in ACTIVE_ENDPOINTS:
        app.register_blueprint(blueprint, url_prefix=url)
    return app
def app():

    db_fd, db_path = tempfile.mkstemp()

    app = create_app({
        'TESTING': True,
        'SQLALCHEMY_DATABASE_URI': 'sqlite:///{}'.format(db_path),
        'SQLALCHEMY_TRACK_MODIFICATIONS': False
    })

    db.create_all()

    yield app

    os.close(db_fd)
    os.unlink(db_path)
Esempio n. 29
0
def create_app(config=DevelopmentConfig):
    app = Flask(__name__)
    migrate = Migrate(app, db)
    csrf = CSRFProtect(app)
    app.config.from_object(config)
    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.login_message = "Ingrese para acceder a esta pagina."

    login_manager.init_app(app)
    db.init_app(app)
    ma.init_app(app)
    csrf.init_app(app)
    migrate.init_app(app, db)

    with app.app_context():
        db.create_all()

    # register each active blueprint
    for url, blueprint in ACTIVE_ENDPOINTS:
        app.register_blueprint(blueprint, url_prefix=url)

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

    # ruta principal de la pagina
    @app.route('/', methods=['GET'])
    def index():
        last_products = get_last_products()
        random_cat = get_random_categories()
        categories = get_all_categories()
        my_info = {
            "products": last_products,
            "random_cat": random_cat,
            "categories": categories
        }
        return render_template("index.html", my_info=my_info)

    # Varables globales para ser usadas en cualquier plantilla
    @app.context_processor
    def global_variables():
        categories = get_all_categories()
        basics = {"categories": categories}
        return dict(basics=basics)

    return app
Esempio n. 30
0
def create_app(config=DevelopmentConfig):
    app = Flask(__name__)
    csrf = CSRFProtect(app)
    app.config.from_object(config)
    db.init_app(app)
    ma.init_app(app)
    csrf.init_app(app)

    with app.app_context():
        db.create_all()

    # register each active blueprint
    for url, blueprint in ACTIVE_ENDPOINTS:
        app.register_blueprint(blueprint, url_prefix=url)

    csrf.exempt(products)
    return app
def create_app(config=DevelpmentConfig):
    app = Flask(__name__)
    migrate = Migrate(app, db)
    csrf = CSRFProtect(app)
    app.config.from_object(config)


    login_manager = LoginManager()
    login_manager.login_view = "auth.login"
    login_manager.init_app(app)
    
    db.init_app(app)
    ma.init_app(app)    
    csrf.init_app(app)
    migrate.init_app(app, db)
    
    @app.template_filter('datetimeformat')
    def datetimeformat(value, format="%Y"):
        return value.strftime(format)
    


    with app.app_context():
        db.create_all()

    # register each active blueprint
    for url, blueprint in ACTIVE_ENDPOINTS:
        app.register_blueprint(blueprint, url_prefix=url)

    #This line disable csrf, I have a problem with addStock because it
    csrf.exempt(auth)
    @login_manager.user_loader
    def load_user(user_id):
        # since the user_id is just the primary key of our user table,
        # use it in
        # the query for the user
        return User.query.get(int(user_id))
    
    
    @login_manager.unauthorized_handler
    def unauthorized():
        # do stuff
        return redirect(url_for("products.catalog"))
    
    return app
Esempio n. 32
0
def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)

    with app.app_context():
        db.create_all()
        app.register_blueprint(dir.bp)
        app.register_blueprint(details.bp)
        app.register_blueprint(disk_usage.bp)
        app.register_blueprint(delete.bp_file)
        app.register_blueprint(delete.bp_dir)
        app.register_blueprint(create.bp)
        app.register_blueprint(root.bp)
        app.register_blueprint(swagger.bp, url_prefix=swagger.url)

    return app
Esempio n. 33
0
def setup():
    """Takes an existing DB and reforms/reseeds it.

    Better than reset for use with EB instances, or when the db is
    being accessed.

    """
    # It's a little gross doing this on AWS, but here it is:

    from app.db import db

    conn = db.engine.connect()
    conn.execute("commit;")
    conn.execute("drop schema public cascade;")
    conn.execute("create schema public;")
    db.session.rollback()
    db.create_all()

    seed()
Esempio n. 34
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    config[config_name].init_app(app)

    db.init_app(app)
    login_manager.init_app(app)

    app.register_blueprint(home_blueprint)
    app.register_blueprint(category_blueprint)
    app.register_blueprint(quiz_blueprint)
    app.register_blueprint(auth_blueprint, url_prefix='/auth')
    app.register_blueprint(api_blueprint, url_prefix='/api/v1.0')

    with app.app_context():
        db.create_all()
        db.session.commit()

    return app
Esempio n. 35
0
	def setUp(self):
		db.create_all()
Esempio n. 36
0
import logging
import os
import re

from flask import Flask, request, abort
from flask.ext.markdown import Markdown

from app.db import db, DataSet, Vote
from app.route import routes


app = Flask(__name__)
app.config.from_object('app.settings')
Markdown(app)

db.init_app(app)
db.app = app
db.create_all()
app.register_blueprint(routes)

app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)


@app.before_request
def before_request():
    if any(re.match(re.escape(ip).replace('\*', '\d+'), request.access_route[-1])
           for ip in os.environ.get('BAN_IPS', '').split(',')):
        abort(403)
Esempio n. 37
0
 def setUp(self):
     self.app = create_app(config='config/test.py')
     db.create_all(app=self.app)
Esempio n. 38
0
def setUpDB(self):
    with self.app.app_context():
        db.create_all()
 def setUp(self):
     db.create_all()
     self.seed()
Esempio n. 40
0
    def setUp(self):
        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()

        db.create_all()