def create_app(self):
     """ Set up an app object with testing config """
     app = Flask(__name__)
     app.config.from_object("config")
     db.init_app(app)
     app.db = db
     return app
Esempio n. 2
0
def main():
    """Main entry point for script."""
    bcrypt = Bcrypt()
    db = SQLAlchemy()
    db.init_app(app)
    with app.app_context():
        db.metadata.create_all(db.engine)
        if User.query.all():
            print('A user already exists! Create another? (y/n):')
            create = input()
            if create == 'n':
                return

        print('Enter username: '******'Enter email: ')
        email = input()
        password_hash = getpass()
        assert password_hash == getpass('Password (again):')

        user = User(username=username,
                    email=email,
                    password_hash=bcrypt.generate_password_hash(
                        password_hash).decode('utf-8'),
                    authenticated=True)
        db.session.add(user)
        db.session.commit()
        print('User added.')
Esempio n. 3
0
def register_extensions(app: Flask):
    """组件初始化"""

    # SQLAlchemy组件初始化
    from app import db

    db.init_app(app)

    # redis组件初始化
    global redis_client
    redis_client = StrictRedis(host=app.config['REDIS_HOST'],
                               port=app.config['REDIS_PORT'],
                               decode_responses=True)
    # 添加转换器
    from utils.converters import register_converters
    register_converters(app)

    # 数据迁移组件初始化
    Migrate(app, db)

    from models import user
    # 添加请求钩子
    from utils.middlewares import get_userinfo
    app.before_request(get_userinfo)

    #
    CORS(app, supports_credentials=True)

    # 导入模型类
    from models import user, article
Esempio n. 4
0
def connect_to_db(app, db_uri=None):
    """Connect the database to our Flask app."""
    app.config['SQLALCHEMY_DATABASE_URI'] = db_uri or os.environ[
        'SQLALCHEMY_DATABASE_URI']
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.app = app
    db.init_app(app)
Esempio n. 5
0
def create_app(test_config=None):
    flaskapp = Flask(__name__, instance_relative_config=True)
    flaskapp.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(flaskapp.instance_path, 'historailsdb.sqlite'),
    )

    flaskapp.config['UPLOAD_FOLDER'] = '/data/trainy/uploads'
    flaskapp.config['FROM_YEAR'] = '1855'
    flaskapp.config[
        'ACCESS_TOKEN'] = 'pk.eyJ1IjoibnVtZmFyIiwiYSI6ImNqN2F2NXdhcjBlcGMzMnN0a2wxaDd3YnoifQ.HZKACURfmAwSBLKkGVOprA'
    flaskapp.config['ALLOWED_EXTENSIONS'] = set(['csv', 'txt'])
    if test_config is None:
        flaskapp.config.from_pyfile('config.py', silent=True)
    else:
        flaskapp.config.update(test_config)

    try:
        os.makedirs(flaskapp.instance_path)
    except OSError:
        pass

    from app import db
    db.init_app(flaskapp)

    from app import auth, historails
    flaskapp.register_blueprint(auth.bp, url_prefix='/')
    flaskapp.register_blueprint(historails.bp)
    flaskapp.add_url_rule('/', endpoint='index')

    return flaskapp
Esempio n. 6
0
def register_extensions(app):
    login.init_app(app)
    login.login_view = 'main.login'  #type: ignore
    bootstrap.init_app(app)
    db.init_app(app)
    with app.app_context():
        if db.engine.url.drivername == 'sqlite':
            migrate.init_app(app, db, render_as_batch=True)
        else:
            migrate.init_app(app, db)
    csrf.init_app(app)
    sitemap.init_app(app)
    cache.init_app(app, config=app.config)

    def fetch_token(name):
        item = oauth.models.OAuth1Token.query.filter_by(
            name=name,
            user_id=(getattr(current_user, 'id', False)
                     or g.current_id)).first()
        if item:
            return item.to_token()

    oauth_client.init_app(app, fetch_token=fetch_token, cache=cache)
    oauth_client.register(
        name='schoology',
        api_base_url='https://api.schoology.com/v1/',
        request_token_url='https://api.schoology.com/v1/oauth/request_token',
        access_token_url='https://api.schoology.com/v1/oauth/access_token',
        authorize_url='https://www.schoology.com/oauth/authorize',
        client_id=app.config['SCHOOLOGY_CLIENT_ID'],
        client_key=app.config['SCHOOLOGY_CLIENT_SECRET'])
Esempio n. 7
0
 def setUp(self):
     self.driver = webdriver.Chrome()
     db.init_app(app)
     self.username = '******'
     self.password = '******'
     self.email = '*****@*****.**'
     self.driver.maximize_window()
def create_app(test_config=None):
  app = Flask(__name__, instance_relative_config=True)
  app.config.from_mapping(
    SECRET_KEY="dev",
    DATABASE=os.path.join(app.instance_path, "app.sqlite"),
  )

  if test_config is None:
    app.config.from_pyfile("config.py", silent=True)
  else:
    app.config.update(test_config)


  try:
    os.makedirs(app.instance_path)
  except OSError:
    pass

  @app.route("/testpage")
  def hello():
    return "Hello, World!"

  from app import db
  db.init_app(app)
  from app import auth
  app.register_blueprint(auth.bp)
  
  return app
Esempio n. 9
0
def create_app(test_config=None):
    """Create and configure an instance of the Flask application."""
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        # a default secret that should be overridden by instance config
        #
        SECRET_KEY="dev",
        # store the database in the instance folder
        DATABASE=os.path.join(app.instance_path, "zndt.sqlite"),
    )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile("config.py", silent=True)
    else:
        # load the test config if passed in
        app.config.update(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # register the database commands
    from app import db

    db.init_app(app)

    from app import zndt_isbn
    app.register_blueprint(zndt_isbn.bp)
    app.add_url_rule("/", endpoint="index")

    return app
Esempio n. 10
0
 def setUp(self):
     self.driver = webdriver.Chrome(
         executable_path=os.path.join(basedir, 'chromedriver.exe'))
     if not self.driver:
         self.skipTest
     else:
         db.init_app(app)
         db.create_all()
         db.session.query(User).delete()
         db.session.query(QA).delete()
         db.session.query(Score).delete()
         u = User(id=1, username="******", email="*****@*****.**")
         u.set_password('test')
         q1 = QA(id=1,
                 question='How good are you?',
                 option1='fantastic',
                 option2='good',
                 option3='bad',
                 option4='awful',
                 answer=1)
         q2 = QA(id=2,
                 question='How is the weather?',
                 option1='sunny',
                 option2='cloudy',
                 option3='rainy',
                 option4='foggy',
                 answer=1)
         db.session.add(u)
         db.session.add(q1)
         db.session.add(q2)
         db.session.commit()
         self.driver.maximize_window()
         self.driver.get('http://localhost:5000/')
Esempio n. 11
0
    def run(self):
        db.init_app(app)
        db.create_all()

        download_ntlk()

        import_combined(os.path.join("data", "Combined.txt"))
Esempio n. 12
0
def create_app():
    app = Flask(__name__)
    bootstrap = Bootstrap(app)
    configure_app(app)
    app.register_blueprint(school_info)
    db.init_app(app)
    return app
Esempio n. 13
0
def create_app():
    # Setup flask app
    flapp = Flask(__name__)
    flapp.config.from_envvar("SCHEDULR_SETTINGS")

    # Setup SQLAlchemy engine & Session class
    flapp.db_engine = create_engine(flapp.config["DB_STRING"])
    flapp.db_Session = scoped_session(sessionmaker(bind=flapp.db_engine))

    init_app(flapp)

    # Setup blueprints
    from app.modules import test_module, auth, setup, home, team

    flapp.register_blueprint(test_module.bp, url_prefix="/test")
    flapp.register_blueprint(setup.bp, url_prefix="/setup")
    flapp.register_blueprint(auth.bp, url_prefix="/auth")
    flapp.register_blueprint(team.bp, url_prefix="/team")
    flapp.register_blueprint(home.bp, url_prefix="/")

    # Setup api
    from app.modules.api import (
        me as api_me,
        team as api_team,
        user as api_user,
        project as api_project,
    )

    flapp.register_blueprint(api_me.bp, url_prefix="/api/me")
    flapp.register_blueprint(api_team.bp, url_prefix="/api/team")
    flapp.register_blueprint(api_user.bp, url_prefix="/api/user")
    flapp.register_blueprint(api_project.bp, url_prefix="/api/project")

    return flapp
Esempio n. 14
0
    def setUp(self):
        self.app = create_app('test')

        db.init_app(self.app)
        db.create_all(app=self.app)

        self.client = self.app.test_client()
Esempio n. 15
0
def create_app(config_file):
    app = Flask(__name__)
    #static_folder=STATIC_PATH,
    #static_url_path='',
    #template_folder=TEMPLATE_PATH)

    install_secret_key(app)

    from app import db
    db.app = app
    db.init_app(app)

    # Create in-memory database
    app.config['DATABASE_FILE'] = DATABASE_FILE
    app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
    app.config['SQLALCHEMY_ECHO'] = SQLALCHEMY_ECHO

    init_logging(app)

    build_flask_admin(app)
    build_url_rules(app)
    cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
    #cors = CORS(app)
    app.config['CORS_HEADERS'] = 'Content-Type'

    return app
Esempio n. 16
0
def create_app(test_config=None):

    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'restaurantsmenu.db'),
    )

    if test_config is None:
        # load instance configs
        app.config.from_pyfile('config.py', silent=True)

    else:
        app.config.from_mapping(test_config)
        os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = "1"

    try:
        os.makedirs(app.instance_path)
    except OSError as identifier:
        pass

    db.init_app(app)

    # register blueprints
    app.register_blueprint(views.bp)
    app.register_blueprint(restaurant.bp)
    app.register_blueprint(menu.bp)

    @app.route('/hello')
    def hello():

        return 'hello'

    return app
Esempio n. 17
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev', # 'dev' it should be overridden with a random value when deploying.
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # a simple page that says hello
    @app.route('/')
    def main():
        return 'Flask, app!'

    @app.route('/hello')
    def hello():
        return 'Hello, World!'

    # register the database commands
    from app import db
    db.init_app(app)

    return app
Esempio n. 18
0
    def setUpClass(cls):
        app.config['DEBUG'] = False
        app.config['TESTING'] = True
        cls.DB_PATH = os.path.join(os.path.dirname(__file__), 'data_test.db')
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(cls.DB_PATH)
        celery.conf.update(CELERY_ALWAYS_EAGER=True)
        cls.hostname = 'http://*****:*****@gmail.com', 'username': '******',
                       'password': '******'}
        requests.post(cls.hostname + '/signup', data=signup_data)
Esempio n. 19
0
 def setUp(self):
     #Using chrome driver
     self.driver = webdriver.Chrome(
         executable_path=os.path.join(basedir, 'chromedriver'))
     if not self.driver:
         self.skipTest
     else:
         db.init_app(app)
         db.create_all()
         #If this account already in User table, then delete it.
         u = User.query.filter_by(username='******').first()
         if u != None:
             db.session.delete(u)
             db.session.commit()
         s1 = User(username='******', email='*****@*****.**', mark=1)
         s1.set_password('password')
         db.session.add(s1)
         line = '1: HTML stands for?'
         q = questions.query.filter_by(content=line).first()
         #If this questions already in questions table, then delete it
         if q != None:
             db.session.delete(q)
             db.session.commit()
         q1 = questions(content=line, stand_answer='a', mark=1, tag='HTML1')
         db.session.add(q1)
         db.session.commit()
         self.driver.maximize_window()
         self.driver.get('http://localhost:5000/')
Esempio n. 20
0
def create_app(environemnt):
    """
    App factory for the server.

    Instantiates a Flask object.
    Configures the app according to the environment.
    Initializes the extensions.
    Adds the middleware to check headers.
    Returns the app instance.

    :param: environment
        Environemnt to configure the server to
    :returns:
    """
    app = Flask(__name__)
    app.config.from_object(cfg_map[environemnt])
    app.redis = Redis.from_url(app.config.get("REDIS_URL"))
    app.task_queue = Queue(app.config.get("REDIS_QUEUE_NAME"),
                           connection=app.redis)
    mongo_client = MongoClient(
        app.config.get("MONGO_URI"),
        authSource=app.config.get("MONGO_AUTH_SOURCE"),
    )
    app.mongo = mongo_client[app.config.get("MONGO_DATABASE")]

    from app import bcrypt
    from app import cors
    from app import db
    from app import migrate

    db.init_app(app)
    cors.init_app(app, resources={r"/*": {"origins": "*"}})
    bcrypt.init_app(app)
    migrate.init_app(app, db)

    from app.api import api

    api.init_app(app)

    from app.api.auth.models import Token  # noqa: F401
    from app.api.sentiment.models import Sentiment  # noqa: F401
    from app.api.users.models import User  # noqa: F401

    @app.before_request
    def check_headers():
        if ("swagger" not in request.path and "admin" not in request.path
                and request.method != "OPTIONS"):
            accepts = request.headers.get("Accept")
            if not accepts or accepts != "application/json":
                abort(415, "Only content type supported is application/json")
            if request.method in ["POST", "PUT"]:
                content_type = request.headers.get("Content-Type")
                if not content_type or content_type != "application/json":
                    abort(
                        415,
                        "POST/PUT requests should define Content-Type header",
                    )

    return app
 def tearDown(self):
     """
     Ensures that the database is emptied for next unit test
     """
     self.app = Flask(__name__)
     db.init_app(self.app)
     with self.app.app_context():
         db.drop_all()
Esempio n. 22
0
 def setUp(self):
     self.flapp = create_app('testing')
     self.app = self.flapp.test_client()
     # self.db.session.expire_all()
     # self.db.drop_all()
     db.init_app(self.flapp)
     with self.flapp.app_context():
         db.create_all()
 def setUp(self):
     self.app = Flask(__name__)
     self.app.config[
         'SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database/db-test.sqlite'
     self.app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
     db.init_app(self.app)
     with self.app.app_context():
         db.create_all()
Esempio n. 24
0
 def setUp(self):
     self.flapp = create_app('testing')
     self.app = self.flapp.test_client()
     # self.db.session.expire_all()
     # self.db.drop_all()
     db.init_app(self.flapp)
     with self.flapp.app_context():
         db.create_all()
Esempio n. 25
0
 def setUp(self):
     cache.clear()
     db.init_app(app)
     db.create_all()
     self.user = User.create(email="m",
                             name="m",
                             password=encrypt_password("m"),
                             active=True)
Esempio n. 26
0
    def create_app(self):
        test_app = Flask(__name__, template_folder='app/templates')
        test_app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
        test_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

        db.init_app(test_app)
        test_app.register_blueprint(main_module)
        return test_app
Esempio n. 27
0
def setup_app():
    auth = HTTPBasicAuth()
    app.config['DEBUG'] = False
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    app.register_blueprint(api_bp)
    db.init_app(app)

    return app
 def setUp(self):
     """
     Creates a new database for the unit test to use
     """
     self.app = Flask(__name__)
     self.app.config.from_object('app.test_config')
     db.init_app(self.app)
     with self.app.app_context():
         db.create_all()
Esempio n. 29
0
    def create_app(self):

        # pass in test configurations
        config_name = 'testing'
        app = create_app(config_name)
        app.config.update(
            SQLALCHEMY_DATABASE_URI='mysql://root@localhost/hrequests-test')
        db.init_app(app)
        return app
def client():
    app = create_app({"TESTING": True,
                      'SQLALCHEMY_DATABASE_URI': 'sqlite:///' + os.path.join(basedir, TEST_DB),
                      'DEBUG': False
                      })
    with app.test_client() as client:
        with app.app_context():
            db.init_app(app)
        yield client
Esempio n. 31
0
 def create_app(self):
     app.config['TESTING'] = True
     app.config['LIVESERVER_PORT'] = 8943
     app.config['LIVESERVER_TIMEOUT'] = 10
     db.init_app(app)
     with app.app_context():
         db.create_all()
         self.init_db()
     return app
Esempio n. 32
0
def purge_db():
    db.init_app(app)
    db.drop_all()  
    db.create_all()
    admin = User('admin', 'template','')
    admin.level = 2
    db.session.add(admin)
    db.session.commit()
    print("Zakończono czyszczenie bazy danych")
Esempio n. 33
0
    def setUp(self):
        self.app = create_app('comment')
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.init_app(self.app)
        db.create_all()

        table_structs = self.app.config.get('COMMENT_TABLE_STRUCTS')
        table_structs = copy.deepcopy(table_structs)
        table_structs.pop('__tablename__')
        self.proxy = CommentProxy([key for key, value in table_structs.items()])
Esempio n. 34
0
def db(app, request):
    """Session wide database connection."""
    _db.init_app(app)
    _db.create_all()
    _db.session.commit()
    Role.insert_roles()
    Event.insert_event()

    def teardown():
        _db.session.close_all()
        _db.drop_all()

    request.addfinalizer(teardown)
    return _db
Esempio n. 35
0
 def setUp(self):
     """Pre-test activities."""
     app.testing = True
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
     with app.app_context():
         db.init_app(current_app)
         db.metadata.create_all(db.engine)
         self.db = db
         self.app = app.test_client()
         drop = Drop(drop_id='abcdefghijklmnopqrstuvwxyzabcdefghijklmnopo', message=b"Hello World")
         dropfoo = Drop(drop_id='abcdefghijklmnopqrstuvwxyzabcdefghijklmnfoo', message=b"Bar")
         db.session.add(drop)
         db.session.add(dropfoo)
         db.session.commit()
 def create_app(self):
     app.testing = True
     app.config['SITE_NAME'] = 'www.foo.com'
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
     app.config['WTF_CSRF_ENABLED'] = False
     app.config['HASH_ROUNDS'] = 1
     app.config['FILE_DIRECTORY'] = os.path.abspath(os.path.join(os.path.split(os.path.abspath(__file__))[0], 'files'))
     with app.app_context():
         db.init_app(current_app)
         bcrypt.init_app(current_app)
         login_manager.login_view = "login"
         self.db = db
         self.app = app.test_client()
     return app
Esempio n. 37
0
def create_app(config_file, logging_config):

	with open(logging_config, 'r')  as cfg_file:
		config = yaml.safe_load(cfg_file)
		logging.config.dictConfig(config)

	logger = logging.getLogger(__name__)
	logger.debug('Loaded logger configuration successfully.')

	## Initialize the app and load it's configurations
	app = Flask(__name__.split('.')[0])
	app.wsgi_app = ReverseProxied(app.wsgi_app)

	# Generate the path and load the configuration
	logger.debug('Loading configuration file %s', config_file)

	app.config.from_pyfile(config_file)

	#
	# We now have a good app running
	# 	We can start loading blueprints and extensions
	#
	logger.debug('Loading SQLAlchemy databse with URI : {}' \
		.format(app.config['SQLALCHEMY_DATABASE_URI'])
	)

	from app import db
	db.init_app(app)
	logger.debug('Initialised SQLAlchemy successfully')

	# Set up Flask-DebugToolbar. If DEBUG is on then the toolbar will be inject into
	# the templates automatically
	from flask_debugtoolbar import DebugToolbarExtension

	toolbar = DebugToolbarExtension(app)
	logger.debug('Loaded Flask-Debug-Toolbar successfully')

	## Register our extra template filters
	from .template_filters import register_filters
	register_filters(app)
	logger.debug('template filters loaded successfully.')

	# load the application blueprints
	from app.computer.views import computer
	app.register_blueprint(computer)

	from app.computer.api import api
	app.register_blueprint(api, url_prefix = '/api')

	return app
 def create_app(self):
     app.testing = True
     app.config["SITE_NAME"] = "www.foo.com"
     app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
     app.config["WTF_CSRF_ENABLED"] = False
     app.config["HASH_ROUNDS"] = 1
     app.config["FILE_DIRECTORY"] = os.path.abspath(
         os.path.join(os.path.split(os.path.abspath(__file__))[0], "files")
     )
     with app.app_context():
         db.init_app(current_app)
         bcrypt.init_app(current_app)
         login_manager.login_view = "login"
         self.db = db
         self.app = app.test_client()
     return app
Esempio n. 39
0
def search_youtube(query, youtube):
	"""return video titles and IDs for a search query term"""
	db.init_app(app)
	db.create_all()
	videos = {}
	response = youtube.search().list(
    q=query,
    part="id,snippet",
	).execute()
	total_results = response['pageInfo']['totalResults']
	for i in response['items']:
		channel_title = i['snippet']['channelTitle']
		channel_id = i['snippet']['channelId']	
		publish_date = i['snippet']['publishedAt']
		video_title = i['snippet']['title']
		video_id = i['id']['videoId']
		videos[video_title] = video_id
		comments = get_comments(video_id, youtube)
	return videos
Esempio n. 40
0
def init_db(flask_app):
	logger.info('Initializing database with URI %s'%flask_app.config['SQLALCHEMY_DATABASE_URI'])
	db.init_app(flask_app)
	db.drop_all()
	db.create_all()
Esempio n. 41
0
 def run(self, *args, **kwargs):
     db.init_app(app)
     super(MyServer, self).run(*args, **kwargs)
Esempio n. 42
0
 def setUp(self):
     cache.clear()
     db.init_app(app)
     db.create_all()
     self.user = User.create(email="m", name="m", password=encrypt_password("m"), active=True)
Esempio n. 43
0
 def _init_db(self, app):
     from app import db
     db.init_app(app)
 def create_app(self):
     app = Flask(__name__)
     app.config.from_object("config")
     db.init_app(app)
     app.db = db
     return app
#!/usr/bin/python

""" main.py - handles imports and running the flask application. """

from app import app, db, login_manager

login_manager.init_app(app)

from models import *

db.init_app(app)
db.create_all()
app.test_request_context().push()

from views import *
from auth import *

def main():
    app.run(host='0.0.0.0', port=5000)

if __name__ == '__main__':
    main()
Esempio n. 46
0
 def setUp(self):
     requests.get = mock.MagicMock(side_effect=requests_get_stub)
     db.init_app(app)
     db.create_all()
Esempio n. 47
0
 def create_app(self):
     app.config.from_object(TestConfig)
     db.init_app(app)
     return app
Esempio n. 48
0
def worker_bootstrap(**_):
    db.init_app(current_app)