Example #1
0
def create_app(config_name):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(DevelopmentConfig())
    app.config.from_pyfile('config.py')
    db.init_app(app)
    app.config['TESTING'] = True
    # app name

    @app.errorhandler(404)
    # inbuilt function which takes error as parameter
    def not_found(e):

        # defining function
        flash('404 Page not found')
        return render_template("home/index.html", title='404 page not found')

    login_manager.init_app(app)
    login_manager.login_message = "You must be logged in to access this page."
    login_manager.login_view = "auth.login"

    migrate = Migrate(app, db)

    Bootstrap(app)
    from app import models

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from .home import home as home_blueprint
    app.register_blueprint(home_blueprint)
    return app
Example #2
0
def create_app():
    global _scraper

    app = Flask(__name__)
    app.config.from_object(DevelopmentConfig())
    CORS(app, resources={r'/*': {'origins': '*'}})

    from App import db
    from bson.json_util import dumps, loads

    from .routes import api
    app.register_blueprint(api, url_prefix='/api/v1')  # blueprints for api
    _spiders = _scraper.get_all_spiders()  # get list of all spiders
    if db.mongoatlas.client is not None:
        _spider_col = loads(dumps(db.spider_col.find()))  # db queries

        if len(_spiders) > 0:  # ensuring correct spider on database
            new_spider = [
                s for s in _spiders
                if not any(_s['name'] in s for _s in _spider_col)
            ]  # filter
            if len(new_spider) > 0:
                for n in new_spider:
                    db.spider_col.insert_one(
                        {"name": n})  # adding new if not exist on database
    return app
Example #3
0
def create_app():
    # Define the application object


    # Change to production configuration if in production
    if(os.environ['ENVIRONMENT'] == 'PRODUCTION'):
        #flask_app = Flask(__name__, static_url_path = '/makeuoft/static')
        flask_app = Flask(__name__)
        config_class=ProductionConfig()
        # Line for mounting the app to the /makeuoft domain
        """
        Note: ensure that ProxyPass and ReverseProxyPass are as follows on apache config:
        ProxyPass /makeuoft/static !
        ProxyPass /makeuoft http://127.0.0.1:8181/
        ProxyPassReverse /makeuoft http://ieee.utoronto.ca/makeuoft
        Alias /makeuoft/static /var/www/makeuoft/public_html/static
        """
        flask_app.wsgi_app = ReverseProxied(flask_app.wsgi_app, script_name='/mfthardware')

    else:
        flask_app = Flask(__name__)
        config_class=DevelopmentConfig()


    cors.init_app(flask_app)

    # Configurations taken from function argument
    flask_app.config.from_object(config_class)

    # Initialize the various models with the flask_app
    db.init_app(flask_app)
    migrate.init_app(flask_app, db)

    # Create a LoginManager instance
    login_manager.init_app(flask_app)
    login_manager.login_view = 'auth.login'
    login_manager.login_message= ''


    # Sample HTTP error handling
    @flask_app.errorhandler(404)
    def not_found(error):
        return render_template("404.html"), 404


    # Import a module / component using its blueprint handler variable (mod_auth)
    #from application.mod_auth.controllers import mod_auth as auth_module
    from application.hardware_signout import hardware_signout as hs_module
    from application.auth import auth as auth_module
    from application.api import api as api_module

    # Register blueprint(s) - connects each module to the main flask application
    # app.register_blueprint(xyz_module)

    flask_app.register_blueprint(hs_module)
    flask_app.register_blueprint(auth_module)
    flask_app.register_blueprint(api_module)


    return flask_app
Example #4
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_object(DevelopmentConfig())
    from . import views
    app.register_blueprint(views.bp)

    return app
Example #5
0
def test_output_with_single_migrations():
    output = MockOutput()
    logger = MigrationLogger(out=output, config=DevelopmentConfig())
    logger.log_performed_migrations(
        [Migration(Path('/test/1_create_animals.py'))])

    assert output.value == 'Environment: development\n' \
                           'Performed 1 migration:\n' \
                           '/test/1_create_animals.py'
def set_app_config(app, environment: str):
    config_object = None
    if environment == "development":
        config_object = DevelopmentConfig()
    if environment == "testing":
        config_object = TestingConfig()
    if environment == "production":
        config_object = ProductionConfig()
    if config_object:
        app.config.from_object(config_object)
Example #7
0
def main(args=[]):
    app_port = PORT if len(args)<=1 else args[1]

    environment = os.getenv('TUTUBO_ENV')
    
    config = ProductionConfig() if environment == "PROD" else DevelopmentConfig()
    app = create_app(config)
    
    print("Raising AuthServer in port", app_port)
    app.run(host="0.0.0.0", port=app_port)
Example #8
0
def create_app():
    app = Flask(__name__,
                instance_path=os.path.join(os.path.abspath(os.curdir), 'instance'),
                instance_relative_config=True)

    # configuration
    if os.path.isdir(app.instance_path) and \
            os.path.isfile(os.path.join(app.instance_path, 'config.py')):
        # append instance folder to import search scope
        sys.path.append(app.instance_path)
        from config import ProductionConfig, DevelopmentConfig, TestingConfig

        if app.config['ENV'] == 'production':
            app.config.from_object(ProductionConfig(app))
        elif app.config['ENV'] == 'development':
            app.config.from_object(DevelopmentConfig(app))
        elif app.config['ENV'] == 'testing':
            app.config.from_object(TestingConfig(app))
        else:
            raise Exception(
                'FLASK_ENV only in (production, development, testing). Your FLASK_ENV is: %s'
                % (app.config['ENV']))

    else:
        raise Exception(
            'Copy config.py.example to %s AND rename to config.py' %
            (app.instance_path))

    # logging
    import logging
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    from logging.handlers import TimedRotatingFileHandler
    handler = TimedRotatingFileHandler(**app.config['LOG_PARAMETERS'])
    handler.setLevel(app.logger.level)
    handler.setFormatter(formatter)
    app.logger.addHandler(handler)

    @app.route('/')
    def dashboard():
        app.logger.info("Dashboard")
        return render_template('dashboard.html')

    @app.route('/test')
    def test():
        return render_template('test.html')

    from .blueprints import maintain
    app.register_blueprint(maintain.bp, url_prefix='/maintain')
    app.logger.info("Load maintain blueprint")

    return app
Example #9
0
def create_application():

    # main flask application
    application = Flask(__name__)

    from config import DevelopmentConfig, TestingConfig

    env = os.getenv('FLASK_ENVIRONMENT', 'debug')

    if env.lower() == 'testing':
        application.config.from_object(TestingConfig())
    else:
        application.config.from_object(DevelopmentConfig())

    # registering blueprints
    from api.v1 import tasks
    application.register_blueprint(tasks.blueprint, url_prefix='/api/v1/tasks')

    ### swagger specific ###
    SWAGGER_URL = '/swagger'
    SWAGGER_FILE = '../static/swagger.json'
    swagger_blueprint = get_swaggerui_blueprint(
        SWAGGER_URL, SWAGGER_FILE, config={'app_name': "flask-api"})
    application.register_blueprint(swagger_blueprint, url_prefix=SWAGGER_URL)
    ### end swagger specific ###

    @application.route("/")
    def hello():

        message = {
            'status': 200,
            'message': 'API V1.0 IS LIVE ',
        }

        response = Response(json.dumps(message),
                            status=200,
                            mimetype='application/json')
        return response

    @application.errorhandler(404)
    def not_found(error=None):
        message = {
            'status': 404,
            'message': 'Not Found: ' + request.url,
        }
        resp = jsonify(message)
        resp.status_code = 404

        return resp

    return application
Example #10
0
def create_app(test_config=None):
    """Create and configure an instance of the Flask application."""

    app = Flask(__name__)
    if app.config['ENV'] == "production":
        app.config.from_object(ProductionConfig())
    elif app.config['ENV'] == "development":
        app.config.from_object(DevelopmentConfig())

    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    setup_app(app)

    return app
Example #11
0
 def add_user(self, username, password, admin=False):
     new_user = User(
         name=username,
         password=bcrypt.generate_password_hash(
             password,
             DevelopmentConfig().BCRYPT_LOG_ROUNDS
         ).decode('utf-8'),
         admin=admin
     )
     try:
         db.session.add(new_user)
         db.session.commit()
     except Exception as db_exceptions:
         print(db_exceptions)
Example #12
0
def create_app():

    flask_app = Flask(__name__)
    # Change to production configuration if in production
    if (os.environ['ENVIRONMENT'] == 'PRODUCTION'):
        config_class = ProductionConfig()
    else:
        config_class = DevelopmentConfig()

    # Define the application object
    flask_app = Flask(__name__)

    # Configurations taken from function argument
    flask_app.config.from_object(config_class)

    # Initialize the various models with the flask_app
    #db.init_app(flask_app)
    #migrate.init_app(flask_app, db)

    # Create a LoginManager instance
    #login_manager.init_app(flask_app)
    #login_manager.login_view = 'auth.login'
    #login_manager.login_message= ''

    # Sample HTTP error handling
    @flask_app.errorhandler(404)
    def not_found(error):
        return render_template("404.html"), 404

    # Setup the DASH apps
    from application.visualizer.layout import layout as layout
    from application.visualizer.callbacks import register_callbacks as register_callbacks
    register_dashapp(flask_app, 'Visualizer 1', 'visualizer', layout,
                     register_callbacks)

    # Import a module / component using its blueprint handler variable (mod_auth)
    #from application.mod_auth.controllers import mod_auth as auth_module
    from application.home import home as home_module
    #from application.visualizer import dash as dash_visualizer

    # Register blueprint(s) - connects each module to the main flask application
    # app.register_blueprint(xyz_module)

    flask_app.register_blueprint(home_module)
    #flask_app.register_blueprint(auth_module)
    #flask_app.register_blueprint(dash_module)

    return flask_app
Example #13
0
 def decode_auth_token(auth_token):
     """
     Validates the auth token
     :param auth_token:
     :return: integer|string
     """
     try:
         payload = jwt.decode(auth_token, DevelopmentConfig().SECRET_KEY)
         is_blacklisted_token = BlacklistToken.check_blacklist(auth_token)
         if is_blacklisted_token:
             return 'Token blacklisted. Please log in again.'
         return payload['sub']
     except jwt.ExpiredSignatureError:
         return 'Signature expired. Please log in again.'
     except jwt.InvalidTokenError:
         return 'Invalid token. Please log in again.'
Example #14
0
 def encode_auth_token(self, user_id):
     """
     Generates the Auth Token
     :return: string
     """
     try:
         payload = {
             'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1, seconds=0),
             'iat': datetime.datetime.utcnow(),
             'sub': user_id
         }
         return jwt.encode(
             payload,
             DevelopmentConfig().SECRET_KEY,
             algorithm='HS256'
         )
     except Exception as token_exception:
         return token_exception
Example #15
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', )

    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

    from config import DevelopmentConfig
    app.config.from_object(DevelopmentConfig())

    from .auth import init_app as auth_init_app
    auth_init_app(app)

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

    from .auth import auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from .user import user_blueprint
    app.register_blueprint(user_blueprint, url_prefix='/user')

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

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

    return app
Example #16
0
def create_app(config=DevelopmentConfig()):
    app = Flask(__name__)
    CORS(app)
    app.config.from_object(config)
    app.logger.setLevel(logging.DEBUG)
    db = initialize_db(app)

    setup_blueprints(app)
    setup_swaggerui(app)

    @app.route('/static/<path:path>')
    def send_static(path):
        return send_from_directory('static', path)

    # -- Unassigned endpoints
    @app.route('/')
    def hello():
        return "This is the Auth Server!"

    return app
Example #17
0
def create_app(config=DevelopmentConfig()):
    app = Flask(__name__)
    CORS(app)
    app.config.from_object(config)
    app.logger.setLevel(logging.DEBUG)

    db = initialize_db(app)

    # -- Services
    from services.UsersService import UsersService
    from services.VideoService import VideoService
    from services.NotificationService import NotificationService
    user_service = UsersService(app.config['AUTH_SERVER'])
    video_service = VideoService(app.config['MEDIA_SERVER'])
    notification_service = NotificationService(app.config['NOTIF_SERVER'])

    # -- Routes registration
    from routes import auth, monitoring, users, videos

    app.register_blueprint(monitoring.bp_monitor)
    app.register_blueprint(auth.construct_blueprint(user_service))
    app.register_blueprint(users.construct_blueprint(user_service, video_service, notification_service))
    app.register_blueprint(videos.construct_blueprint(video_service, user_service))

    setup_swaggerui(app)

    # -- Unassigned endpoints

    @app.route('/static/<path:path>')
    def send_static(path):
        return send_from_directory('static', path)

    @app.route('/')
    def hello():
        return "This is the Application Server!"

    @app.route('/friendRequests', methods=['POST'])
    def friend_request():
        return "This endpoint will work for sending invites"

    return app
Example #18
0
def create_app(config='production'):
    """
    :config: can be one of ['production', 'development'], or a config object
    """
    if isinstance(config, string_types):
        if config.lower().startswith('dev'):
            config = DevelopmentConfig()
        elif config.lower().startswith('prod'):
            config = ProductionConfig()
        else:
            raise RuntimeError("invalid `config`")

    app = Flask(__name__)
    app.config.from_object(config)
    if app.config.get('STATIC_FOLDER') is None:
        app.config['STATIC_FOLDER'] = app.static_url_path

    from . import main
    app.register_blueprint(main.bp)

    return app
def run(config: Config = DevelopmentConfig()):
    events = EventQueue()
    csv_dir = config.DATA_DIR
    symbols = config.SYMBOLS

    data_handler = GDAXCSVDataHandler(events, symbols, csv_dir)
    strategy = BuyAndHoldStrategy(events, symbols)

    portfolio = Portfolio()
    position_sizer = PositionSizerMock()
    risk_manager = RiskManagerMock()
    portfolio_handler = PortfolioHandler(events, portfolio, position_sizer,
                                         risk_manager)

    execution_handler = SimulatedExecutionHandler(events)
    report_handler = ReportHandler(portfolio)

    engine = BacktestingEngine(events, data_handler, strategy,
                               portfolio_handler, execution_handler,
                               report_handler)

    engine.run()
Example #20
0
def create_app(test_config=None):
    
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
     
    app.config.from_object(DevelopmentConfig())

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

    # Ping pong route
    @app.route('/ping')
    def hello():
        return 'Pong!'
    
    db.init_app(app)
    migrate.init_app(app, db)

    # Uncomment for model imports
    # from .models import *
    
    with app.app_context():
        
        from .routes import auth, index
        from .api import api
        
        app.register_blueprint(auth.bp)
        app.register_blueprint(index.bp)
        app.register_blueprint(api.bp)
        app.add_url_rule('/', endpoint='index')
        
        import error_handlers
                
        return app
Example #21
0
def create_app(config_name):

    app = Flask(__name__, instance_relative_config=True)
    cfg = DevelopmentConfig()
    cfg.init_app(app)
    app.config.from_object(cfg)

    db.init_app(app)
    migrate = Migrate(app, db)

    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from .errors import errors as error_blueprint
    app.register_blueprint(error_blueprint)

    return app
Example #22
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__)
    if test_config:
        app.config.from_object(TestingConfig())
    else:
        app.config.from_object(DevelopmentConfig())

    db = setup_db(app)
    migrate.init_app(app, db)
    CORS(app)

    @app.route('/')
    def index():
        return "Course Management APP"

    #---------------------------------------------------------#
    # Students
    #---------------------------------------------------------#

    @app.route('/students')
    @authorize_user('get:data')
    def get_students():
        items_limit = request.args.get('limit', 3, type=int)
        page_num = request.args.get('page', 1, type=int)
        current_index = page_num - 1
        error = False

        try:
            students = db.session.query(Student).order_by(
                Student.std_id).limit(items_limit).offset(items_limit *
                                                          current_index).all()

            formatted_std = [student.format for student in students]

        except Exception:
            error = True
            print(sys.exc_info())

        if error:
            abort(404)
        else:
            return jsonify({
                "success": True,
                "students": formatted_std,
                "total": len(formatted_std)
            })

    @app.route('/students/<int:student_id>')
    @authorize_user('get:data')
    def get_student_by_id(student_id):
        error = False

        try:
            student = db.session.query(Student).filter(
                Student.std_id == student_id).one_or_none()

            format_student = student.format
        except Exception:
            error = True
            print(sys.exc_info())

        if error:
            abort(404)
        else:
            return jsonify({
                "success": True,
                "student": format_student,
            })

    @app.route('/students/create', methods=['POST'])
    @authorize_user('post:data')
    def create_student():
        body = request.get_json()
        std_fname = body.get('fname')
        std_lname = body.get('lname')
        std_email = body.get('email')
        std_dob = body.get('dob')
        std_gender = body.get('sex')
        std_regno = int(body.get('regno'))

        error = False

        try:
            # instantiate student object
            std = Student(std_regno, std_fname, std_lname, std_email, std_dob,
                          std_gender)
            std.insert()
            students = Student.query.order_by(Student.std_id).all()
            students_list = [student.format for student in students]

        except Exception as e:
            db.session.rollback()
            error = True
            print(sys.exc_info())
        finally:
            db.session.close()

        if error:
            abort(422)
        else:
            return redirect('/students')

    @app.route('/students/<int:student_id>', methods=['PATCH'])
    @authorize_user('patch:data')
    def update_students(student_id):
        body = request.get_json()

        if body:
            email = body.get('email')
        else:
            abort(400)

        error = False

        try:
            std = db.session.get(Student, student_id)
            std.std_email = email
            std.update()
        except Exception as e:
            db.session.rollback()
            error = True
            print(sys.exc_info())

        if error:
            abort(422)
        else:
            return redirect(f'/students/{student_id}')

    @app.route('/students/<int:student_id>', methods=['DELETE'])
    @authorize_user('delete:data')
    def delete_students(student_id):
        error = False

        try:
            std = db.session.get(Student, student_id)
            std.delete()

            updated_students = Student.query.order_by(Student.std_id).all()
            formatted_students = [
                student.format for student in updated_students
            ]
        except Exception as e:
            db.session.rollback()
            print(e)
        finally:
            db.session.close()

        if error:
            abort(404)
        else:
            return redirect('/students')

    #---------------------------------------------------------#
    # Courses
    #---------------------------------------------------------#

    @app.route('/courses')
    @authorize_user('get:data')
    def getCourses():
        error = False

        try:
            courses = db.session.query(Course).order_by(Course.crs_id).all()
            format_courses = [course.format for course in courses]

        except Exception:
            error = True
            print(sys.exc_info())
        finally:
            db.session.close()

        if error:
            abort(404)
        else:
            return jsonify({
                "success": True,
                "courses": format_courses,
                "total": len(courses)
            })

    @app.route('/courses/create', methods=['POST'])
    @authorize_user('post:data')
    def create_courses():
        body = request.get_json()
        crs_title = body.get('title')
        crs_code = body.get('code')
        crs_desc = body.get('desc')
        crs_book = body.get('book')
        crs_lec = int(body.get('lec'))
        crs_room = int(body.get('room'))

        error = False

        try:
            # instantiate course object
            crs = Course(crs_code, crs_title, crs_desc, crs_book, crs_lec,
                         crs_room)
            crs.insert()
            courses = Course.query.order_by(Course.crs_id).all()
            courses_list = [course.format for course in courses]

        except Exception as e:
            db.session.rollback()
            error = True
            print(sys.exc_info())
        finally:
            db.session.close()

        if error:
            abort(422)
        else:
            return redirect('/courses')

    @app.route('/courses/<int:course_id>', methods=['PATCH'])
    @authorize_user('patch:data')
    def update_courses(course_id):
        body = request.get_json()

        if body:
            title = body.get('title')
            book = body.get('book')
        else:
            abort(400)

        error = False

        try:
            crs = db.session.get(Course, course_id)
            crs.crs_title = title
            crs.crs_book = book
            crs.update()
        except Exception as e:
            db.session.rollback()
            error = True
            print(sys.exc_info())

        if error:
            abort(422)
        else:
            return jsonify({'success': True, 'course_id': crs.crs_id})

    @app.route('/courses/<int:course_id>', methods=['DELETE'])
    @authorize_user('delete:data')
    def delete_courses(course_id):
        error = False

        try:
            crs = db.session.get(Course, course_id)
            crs.delete()

            updated_courses = Course.query.order_by(Course.crs_id).all()
            formatted_courses = [course.format for course in updated_courses]
        except Exception as e:
            db.session.rollback()
            print(e)
        finally:
            db.session.close()

        if error:
            abort(422)
        else:
            return jsonify({
                'success': True,
                'deleted_id': crs.crs_id,
                'courses': formatted_courses,
                'total_courses': len(updated_courses)
            })

    @app.errorhandler(AuthError)
    def authError(error):
        return jsonify({
            'success': False,
            'error': error.status_code,
            'message': error.error['description']
        }), error.status_code

    @app.errorhandler(400)
    def bad_request(error):
        return jsonify({
            "success": False,
            "error": 400,
            "message": "Bad Request"
        }), 400

    @app.errorhandler(404)
    def not_found(error):
        return jsonify({
            "success": False,
            "error": 404,
            "message": "Resource Not Found"
        }), 404

    @app.errorhandler(500)
    def server_error(error):
        return jsonify({
            "success": False,
            "error": 500,
            "message": "Internal Server error"
        }), 500

    @app.errorhandler(422)
    def unprocessable(error):
        return jsonify({
            "success": False,
            "error": 422,
            "message": "unprocessable"
        }), 422

    return app
Example #23
0
from flask_marshmallow import Marshmallow
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager, verify_jwt_in_request
from flask_migrate import Migrate

app = Flask(__name__, template_folder='./templates', static_folder='./static')

# Config
app.config.production = False
app.config.development = False
environment = os.getenv("ENVIRONMENT", "development")

if environment == "development":
    from config import DevelopmentConfig
    app.config.from_object(DevelopmentConfig())
    app.config.development = True
    print(f"Theater started with environment = {environment}")
elif environment == "production":
    from config import ProductionConfig
    app.config.from_object(ProductionConfig())
    app.config.production = True
    print(f"Theater started with environment = {environment}")
else:
    raise ValueError(f'"{environment}" not valid environment.')

# Extensions
CORS(app)
api = Api(app)
db = SQLAlchemy(app)
ma = Marshmallow(app)
Example #24
0
# -*- coding: utf-8 -*-
import os
import sys
import inspect
from flask import Flask
from flask_user import UserManager, UserMixin
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_wtf.csrf import CSRFProtect
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from config import DevelopmentConfig, ProductionConfig

db = SQLAlchemy()
config = DevelopmentConfig()
migrate = Migrate(compare_type=True)
csrf_protect = CSRFProtect()
mail = Mail()
bootstrap = Bootstrap()


def create_app(config_settings=DevelopmentConfig):

    app = Flask(__name__, static_url_path='/static')
    app.config.from_object(config_settings)

    db.init_app(app)
    migrate.init_app(app, db)
    csrf_protect.init_app(app)
    mail.init_app(app)
    bootstrap.init_app(app)
Example #25
0
# -*- coding: utf-8 -*-
"""
    bb8 Client API init
    ~~~~~~~~~~~~~~~~~~~

    Copyright 2016 bb8 Authors
"""

import os

from config import DevelopmentConfig, DeployConfig, TestingConfig

config = None

if os.getenv('BB8_TEST', '') == 'true':
    config = TestingConfig()  # pylint: disable=R0204
elif os.getenv('BB8_DEPLOY', '') == 'true':
    config = DeployConfig()  # pylint: disable=R0204
else:
    config = DevelopmentConfig()  # pylint: disable=R0204
Example #26
0
def create_app():
    app = Flask(__name__)
    config = None
    if os.environ["FLASK_ENV"] == "production":
        config = ProductionConfig()
    elif os.environ["FLASK_ENV"] == "development":
        config = DevelopmentConfig()
        print("THIS APP IS IN DEV CONFIGURATION. DO NOT USE IN PRODUCTION.")
    elif os.environ["FLASK_ENV"] == "test":
        config = TestConfig()
        print("THIS APP IS IN TEST CONFIGURATION. DO NOT USE IN PRODUCTION.")
    elif config == None:
        print("NO CONFIGURATION SET.")

    app.config.from_object(config)

    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)
    mail.init_app(app)

    from app.scheduler_tasks.check_studies import check_studies

    if os.environ["FLASK_ENV"] != "test":
        scheduler.api_enabled = True
        scheduler.init_app(app)
        scheduler.add_job(
            id="check_studies_job",
            trigger="cron",
            func=check_studies,
            hour="*",
            minute=5,
            args=[app],
        )
        scheduler.start()
        atexit.register(lambda: scheduler.shutdown(wait=False))

    csrf.init_app(app)
    jwt.init_app(app)

    from app.errors import bp as errors_bp

    app.register_blueprint(errors_bp)

    app.register_blueprint(bp, url_prefix="/")

    from app.auth import bp as auth_bp

    app.register_blueprint(auth_bp, url_prefix="/auth")

    from app.admin import bp as admin_bp

    app.register_blueprint(admin_bp, url_prefix="/admin")

    from app.study import bp as study_bp

    app.register_blueprint(study_bp, url_prefix="/study")

    from app.responses import bp as responses_bp

    app.register_blueprint(responses_bp, url_prefix="/responses")

    from app.api import bp as api_bp

    app.register_blueprint(api_bp, url_prefix="/api")

    # from https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-vii-error-handling
    if not app.debug and not app.testing:
        if app.config["MAIL_SERVER"]:
            auth = None
            if app.config["MAIL_USERNAME"] or app.config["MAIL_PASSWORD"]:
                auth = (
                    app.config["MAIL_USERNAME"],
                    app.config["MAIL_PASSWORD"],
                )

            mail_handler = SMTPHandler(
                mailhost=(app.config["MAIL_SERVER"], app.config["MAIL_PORT"]),
                fromaddr=app.config["MAIL_USERNAME"],
                toaddrs=app.config["ADMIN_EMAILS"],
                subject="User Study Error",
                credentials=auth,
                secure=() if app.config["MAIL_USE_TLS"] else None,
            )
            mail_handler.setLevel(logging.ERROR)
            app.logger.addHandler(mail_handler)

        if not os.path.exists("logs"):
            os.mkdir("logs")
        file_handler = RotatingFileHandler(
            "logs/userstudy.log", maxBytes=10240, backupCount=10
        )
        file_handler.setFormatter(
            logging.Formatter(
                "%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]"
            )
        )
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)

        app.logger.setLevel(logging.INFO)
        app.logger.info("User Study startup")

    return app
Example #27
0
import os
from config import DevelopmentConfig, ProductionConfig
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_socketio import SocketIO, send, emit

app = Flask(__name__)
config = ProductionConfig() if os.environ.get(
    'FLASK_ENV') == 'production' else DevelopmentConfig()
app.config.from_object(config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
socketio = SocketIO(app)

from app import route, models

# route.initiateManifest()
# route.initiateEkspor()

if __name__ == '__main__':
    socketio.run(app)
Example #28
0
model_name = args.model_name

with open(label_file) as file:
    lines = file.readlines()
    label_list = [{
        'label': line.split(':')[0],
        'ClassId': line.split(':')[1].strip('\n')
    } for line in lines]
    label_df = pd.DataFrame(label_list, dtype=str)

species_df = pd.read_csv(args.species_file, dtype=str)
species_df['vnc_id'] = species_df['vnc_url'].apply(
    lambda x: x.split('ID=')[-1])

join_df = species_df.merge(label_df,
                           how='inner',
                           left_on='ClassId',
                           right_on='ClassId')

DBHelper.connect_database(DevelopmentConfig())
for index, row in join_df.iterrows():
    vnc_id = row['vnc_id']
    label = row['label']
    # d =1
    ModelLabel.create(
        DBHelper.get_session(), **{
            'vnc_id': str(vnc_id),
            'label_id': int(label),
            'model_name': model_name
        })
Example #29
0
from application import advisor
from config import DevelopmentConfig



if __name__ == '__main__':
    advisor(config=DevelopmentConfig(),app_name="advisor").run()
Example #30
0
from app import create_app
from config import DevelopmentConfig

if __name__ == '__main__':
    app = create_app(DevelopmentConfig())
    # app.run()
    print(dir(app))